Javascript remove last character from string example; In this tutorial you will learn how to remove the last Character from a String in JavaScript if the last character is anything like comma, slash, dash, underscore, digits etc anything else;
In Javascript we can use the slice() or substring() method to remove the last character from string in Javascript;
1. Using slice() Method
To remove the first and last character from a string, we just need to specify the two arguments in slice method which are startIndex and endIndex.
const str = 'test/';
const withoutLast = str.slice(0, -1);
console.log(withoutLast); // test
Here we have passed two parameters String.slice method are:
- start index – the index (zero-based) at which we begin extraction
- end index – extract characters up to, but not including this index. In our case
-1
means extract up to, but not including the last character
2. Using substring() method
The substring() method also works similar like slice method but in substring negative indexes are treated as 0 so that we need to use str.length-1 to get the endIndex.
const str = 'test/';
const withoutLast = str.substring(0, str.length - 1);
console.log(withoutLast); // test
The substring method takes the start and end indexes as parameters and does not mutate the original string.