How to remove the last character from a string in JavaScript

How to remove the last character from a string in JavaScript

In this tutorial, we are going to learn about different ways to remove the last character from string in JavaScript.

First way: slice method

In JavaScript, we have slice() method by using that we can remove the last character from a string instead of modifying the original string.

Example:

let str  = 'hello/';


console.log(str.slice(0,str.length-1));

//output-->   'hello'

slice method takes two arguments startIndex and endIndex.

startIndex is included in the output.

endIndex is not included in the output.

Second way: substring method

Example:

let str  = 'hello/';

console.log(str.substring(0,str.length-1));

//output--> 'hello'

substring method also works similar like slice method but in substring method if argument one index is greater than argument two index then arguments are swapped.

Example:

let str  = 'hello/';

//this syntax also gives correct answer
// because argument 1 index is greater than argument 2
console.log(str.substring(str.length-1,0));

//output--> 'hello'