Remove the Last Character From A JavaScript String
In this tutorial, we'll discuss three different methods for removing the last character from a string using JavaScript. The methods we'll explore are slice()
, substring()
, and substr()
.
All methods contain two optional parameters:
start
(optional): The starting position of the string. This value uses a zero-based index, meaning the starting value is 0. If this parameter is omitted, 0 will be assumed by default.end
(optional): The ending position of the string. This value also uses a zero-based index, so the end of the string is the string's value length minus one.
The slice()
method
The slice()
method takes the text between the specified indexes (the start and end values) and returns a new string. To remove the last character from a string, we could use the following code:
var str = "Hello1";
str = str.slice(0, str.length - 1);
console.log(str);
// Hello
In this example, the length of the string is determined, followed by -1 which cuts the last character of the string.
The reason why I mention this method first is that it's my favorite! You can shorten this code a bit by setting a negative index as the end value instead of determining the string's length first and then trimming off the end:
var str = "Hello1";
str = str.slice(0, -1);
console.log(str);
// Hello
There are no real speed benefits to this, but it does help keep the code a bit slimmer which is always a win!
You can also remove the last character from the string by assigning its result to another variable, keeping the original version of the string intact for later use, if needed:
var str = "Hello1";
var new_str = str.substring(0, str.length - 1);
console.log(str);
console.log(new_str);
// Hello1
// Hello
The substring()
method
The substring()
method returns part of the string between the start and end parameter values specified. This can be used as follows to remove the last character from a string:
var str = "Hello1";
str = str.substring(0, str.length - 1);
console.log(str);
// Hello
The substr()
method
The substr()
method returns part of the string, starting with the specified start value and ending with the end value, respectively:
var str = "Hello1";
str = str.substr(0, str.length - 1);
console.log(str);
// Hello
Take note that thesubstr()
method isn't technically deprecated, but is considered a legacy function, and using it should be avoided whenever possible. Use thesubstring()
method instead.
Conclusion
That's all there is to remove the last character from a string in JavaScript. Use the method that works best for you and your applications. Just remember the benefits of each.
Comments
There are no comments yet. Start the conversation!