Remove Last Character from String in JavaScript

In this tutorial, we will learn how to remove the last character from a string in JavaScript.

 

With the JavaScript slice() Function

The easiest way to take away the last character in a string is to use the JavaScript slice() function like this:

 

var str = 'I am a string';

var new_str = str.slice(0, -1);

console.log(new_str);
I am a strin

 

slice() removes a range of indexes from a string. The first argument is the start index and the second is the end index of the removal range. Therefore, we can supply 0 then -1 to select the last index of the string. slice() does not affect the original variable so you will need to store the result in a new one.

 

With the JavaScript substring() Function

substring() returns part of a string based on a range. Therefore we can select all of the characters in the string based on its length minus 1 to remove the last character.

 

var str = 'I am a string';

var new_str = str.substring(0, str.length -1);

console.log(new_str);
I am a strin

 

As with slice(), the result will need to be stored in a new variable.

string