How to remove the last character of a string in JavaScript
By Flavio Copes
Learn how to remove the last character of a string in JavaScript with the slice() method, passing 0 and -1, which returns a new unmodified string.
To remove the last character from a string, use the slice() method of the string, passing 0 as the start and -1 as the end:
const text = 'Hello Roger!'
const editedText = text.slice(0, -1) //'Hello Roger'
The two parameters are the start index and the end index. slice() extracts the characters between them, and the character at the end index is excluded.
A negative end counts from the end of the string. Passing -1 means “stop one character before the end”, which drops the last character. Passing -2 drops the last two:
'Hello Roger!'.slice(0, -2) //'Hello Roge'
You’d get the same result with text.slice(0, text.length - 1), but -1 is shorter and says the same thing.
Strings are immutable
Note that the slice() method does not modify the original string.
It creates a new string, and this is why I assign it to a new variable in the above example. If you want to replace the original value, declare the variable with let and reassign it.
This is true for every string method in JavaScript. None of them changes the string in place.
Why not substring()?
substring() looks similar, but it treats negative numbers as 0:
'Hello Roger!'.substring(0, -1) //''
You get an empty string, which is rarely what you want. Stick with slice() when you count from the end.
Watch out for emoji
Here’s the pitfall. slice() works on UTF-16 code units, and some characters, like emoji, take two of them. Remove the “last character” of a string ending with an emoji and you cut it in half, leaving a broken lone surrogate behind:
'hey🙂'.slice(0, -1) //'hey\ud83d'
The fix is to split the string with Array.from() first, which understands these pairs and splits by full characters:
Array.from('hey🙂').slice(0, -1).join('') //'hey'
If your strings are plain text without emoji, slice(0, -1) is all you need. One last edge case: calling it on an empty string returns an empty string, no error, so you don’t need to guard against that.
Related posts about js: