Sometimes, we want to remove the first and last characters of a JavaScript string.
In this article, we’ll look at how to remove the first and last characters of a JavaScript string.
Use the String.prototype.substring Method
We can use the JavaScript string’s substring method to return a string that’s between the start and end indexes.
The start index is included but the end index isn’t.
To use it, we write:
const str = "/installers/";
const result = str.substring(1, str.length - 1);
console.log(result);
to call substring with the start and end index respectively.
str.length — 1 is the end index because we only want to return the string up to the 2nd last character.
Therefore result is 'installers' .
Use the String.prototype.slice Method
We can also use the JavaScript string’s slice method to return a string between the start and end indexes.
For instance, we can write:
const str = "/installers/";
const result = str.slice(1, -1);
console.log(result);
to call slice with the start and end index of the str we want to include in result .
Index -1 is the last index of the string, and it’s not included in the returned string like substring .
Therefore, result is the same as the last example.
Conclusion
We can use the JavaScript string slice or substring method to extract a string within the given start and end indexes.
The character at the end index isn’t included in the returned string with either method.