How to remove the last character from a string in JavaScript

You can use the slice() and substring() methods to remove one or more characters from the end of a string in JavaScript.

Remove the last character from a string

You can use the slice() method to remove the last character from a string, passing it 0 and -1 as parameters:

const str = 'JavaScript'

const result = str.slice(0, -1)
console.log(result) // JavaScrip

The slice() method extracts a part of a string between the start and end indexes, specified as first and second parameters. It returns the extracted part as a new string and does not change the original string.

Indexes in JavaScript are zero-based. The first character in a string has an index of 0, and the last has an index of str.length - 1.

We passed -1 as an end index to the slice() method to exclude the last character t from the returned string. The negative index of -1 specifies that we want to skip the ending character and get a new string containing the rest.

Alternatively, you could use the substring() method to remove the last character from a string, as shown below:

const str = 'JavaScript'

const result = str.substring(0, str.length -1)
console.log(result) // JavaScrip

The substring() method extracts characters between the start and end indexes from a string and returns the substring.

Remove the last N characters from a string

You can also use the slice() method to remove the last N characters from a string in JavaScript:

const str = 'JavaScript'

const removed2 = str.slice(0, -2)
console.log(removed2) // JavaScri

const removed6 = str.slice(0, -6)
console.log(removed6) // Java

const removed9 = str.slice(0, -9)
console.log(removed9) // J

The substring() method can also be used to remove the last N characters from a string:

const str = 'JavaScript'

const removed4 = str.substring(0, str.length - 4)
console.log(removed4) // JavaSc

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.