How to remove the last character from a string in JavaScript
In this tutorial, we are going to learn about two different ways to remove the last character from a string in JavaScript.
Using slice() method
In JavaScript, we have a built-in slice()
method by using that we can remove the last character from a string.
Here is an example:
let str = 'hello/';
console.log(str.slice(0,str.length-1));
Output:
'hello'
In the above code, we have passed two arguments to the slice() method. so it begins the slicing at index position 0, and extracts before the last character index.
Similarly, we can also use the substring()
method to remove the last character of a given string.
Example:
let str = 'hello/';
console.log(str.substring(0,str.length-1));
Note: The 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.