Anjan Dutta

Remove the last character of a string in javascript

Remove the last character of a string in javascript

There are three functions we can use to remove the last character of a string in javascript. Those are the substring(), slice() and substr() method.

Using substring() method

The substring() method returns the characters from a string between a specified start and end index. The returned characters include the start index but not the end index.

Note: an index starts from 0.

var str = "123456789";
var res = str.substring(1, 4);
console.log(res);
// > 234

Code to remove the last character.

var str = 'Hello World';
str = str.substring(0, str.length - 1);
console.log(str);
// > Hello Worl

Using slice() method

The slice() method returns the characters from a string between a specified start and end index. The returned characters include the start index but not the end index.

Note: an index starts from 0.

var str = "Hello world!";
var res = str.slice(1, 5);
// > ello

Code to remove the last character.

var str = 'Hello World';
str = str.slice(0, str.length - 1);
console.log(str);
// > Hello Worl

Using substr() method

The substr() method returns a specified number of characters from a string beginning at the specified index.

Note: an index starts from 0.

var str = "Hello world!";
var res = str.substr(1, 4);
// > ello

Code to remove the last character.

var str = 'Hello World';
str = str.substr(0, str.length - 1);
console.log(str);
// > Hello Worl