How to remove the last character of a string in Javascript

How to remove the last character of a string in Javascript?

Using slice

The most efficient way is to use the slice(startIndex, no of items) method of String in javascript which takes 2 parameters.

List of different string methods.

First, the start index from where the character has to be removed and second number of items which has to be removed.

Passing -1 in the second parameter will remove the characters from the end.

-1 for last character, -2 for last two characters and so on.

const str = 'prashant';
const editedStr = str.slice(0, -1);  // 'prashan'

On thing you should take note of here is that, slice method does not mutates the original string, it returns a copy of the modified string.

Using substring.

Another way is using the substring(start, end) method which returns all the characters of the string between the start and the end index.

const str = 'prashant';
const editedStr = str.substring(0, str.length - 1);  // 'prashan'

It also does not modifies the original string.