In this article, I am going to show you some ways to remove the last character from a string. There is a way that you do not need to care about the length of the string.
Method #1: slice(startIndex, endIndex)
String.prototype.slice() method returns the part of the string between the start (inclusive) and the end (exclusive) indexes or the end of the string if the end index is omitted.
To remove the last character from the string, you need to slice it from the beginning to the character at the
string.length - 2 index, since the index of the last index is
string.length - 1.
const string = 'Hello World'; string.slice(0, string.length - 1); // 'Hello Worl'
An important note that you should know is if the end index is a negative number, let’s say
-N, it acts like
string.length - N, then the returned string will not contain the last
N characters. By using this cool feature, you do not need to care about the string’s length. So you have the code:
string.slice(0, -1); // 'Hello Worl'
Method #2: substring(startIndex, endIndex)
Similar to the
String.prototype.slice() method, you can use the
String.prototype.substring() method instead. But note that this method does not support the special negative index.
const string = 'Hello World'; string.substring(0, string.length - 1); // 'Hello Worl'
Method #3: substr(startIndex[, length]) [DEPRECATED]
String.prototype.substr() method returns the part of the string starting at the start index with the specified length. This method is deprecated so you should avoid using it.
There are 2 ways to remove the last character from a string, but in my opinion, the
Method #1 that using the
slice(0, -1) method is the best because of its convenience.