Remove last character from a string in JavaScript
This post will discuss how to remove the last character from a string in JavaScript.
It is not possible to in-place remove characters from a string since strings are immutable in JavaScript. The idea is to create a new string instead.
There are several ways to do that in JavaScript using the substring(), slice(), or substr() method.
1. Using substring() method
The substring() method returns the part of the string between the specified indexes. You can use it as follows to remove the last character from a string:
|
1 2 3 4 5 6 7 8 |
var str = 'Java8'; str = str.substring(0, str.length - 1); console.log(str); /* Output: Java */ |
2. Using slice() method
The slice() method extracts the text from a string between the specified indexes and returns a new string. You can use the following code, which removes the last character from the string:
|
1 2 3 4 5 6 7 8 |
var str = 'Java8'; str = str.slice(0, str.length - 1); console.log(str); /* Output: Java */ |
The following example uses slice() with negative indexes.
|
1 2 3 4 5 6 7 8 |
var str = 'Java8'; str = str.slice(0, -1); console.log(str); /* Output: Java */ |
3. Using substr() method
The substr() method returns a portion of the string, starting at the specified index and extract the specified number of characters. The substr() method is considered a legacy function, and we should use the substring() method instead.
|
1 2 3 4 5 6 7 8 |
var str = 'Java8'; str = str.substr(0, str.length - 1); console.log(str); /* Output: Java */ |
That’s all about removing the last character from a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)