How to remove the last character from a string in JavaScript

OpenJavaScript 0
Reading Time: < 1 minute 🕑

Last updated: March 8, 2022.

You may sometimes come across the need to remove the last character from a string in JavaScript.

Unfortunately, the array method .pop(), which does this default, cannot be applied to string data.

Instead, it is necessary to do a little more work using the slice string method:

const myString = "Learning JavaScript, one method at a time!"

const myStringSliced= myString.slice(0, -1);

console.log(myStringSliced); // "Learning JavaScript, one method at a time"

The first and second argument of the slice method specify from which position to which position the string should be sliced. The string does not need to be shortened at the beginning, so 0, the first character position, is entered.

The -1 in the second argument position may be confusing. This is because slice supports negative indexing. So -1 specifies 1 character from the end, -2 two characters from the end, etc.

So with the syntax myString.slice(0, -1) we are specifying that we want to create a new string that begins at position 0 and 1 from the end of myString.