Skip to Content

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 the substr() method isn't technically deprecated, but is considered a legacy function, and using it should be avoided whenever possible. Use the substring() 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.

Last Updated: August 19, 2022
Created: August 07, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.