Wed Oct 06 2021·2 min read
Photo by Katerina Kerdi
To remove the first and last characters from a string, call the
method, passing it
-1 as parameters, e.g.
str.slice(1, -1). The
slice method returns a new string containing the extracted section from the
const str = 'abcd'; const withoutFirstAndLast = str.slice(1, -1); console.log(withoutFirstAndLast); // 👉️ bc
We passed the following parameters to the String.slice method:
-1means go up to, but not including the last character of the string
str.length - 1is the same. We instruct the
slicemethod to go up to, but not including the last character in the string.
slice method on an empty string does not throw an error, it
returns an empty string.
const str = ''; const withoutFirstAndLast = str.slice(1, -1); console.log(withoutFirstAndLast); // 👉️ ""
An alternative approach to remove the first and last characters from a string
is to use the
const str = 'abcd'; const withoutFirstAndLast = str.substring(1, str.length - 1); console.log(withoutFirstAndLast); // 👉️ bc
In the example above, the
method achieves the same result as the
The first parameter it takes is the start index (zero-based) and the second is the end index (up to, but not including).
String.substringmethod it treats it as if you passed
0, which is very confusing.
My personal preference is to use the
String.slice method, because it's more
String.substring in many scenarios.
An example of this confusing behavior is - if you pass a greater
start index to the
String.substring method, it just reverses them,
String.slice method returns an empty string.
If you want to read more about the differences between the methods, check out this section in the MDN docs.
I'll send you 1 email a week with links to all of the articles I've written that week