Remove First and Last Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

Remove First and Last Characters from a String #

To remove the first and last characters from a string, call the slice() method, passing it 1 and -1 as parameters, e.g. str.slice(1, -1). The slice method returns a new string containing the extracted section from the original string.

index.js
const str = 'abcd'; const withoutFirstAndLast = str.slice(1, -1); console.log(withoutFirstAndLast); // ๐Ÿ‘‰๏ธ bc

We passed the following parameters to the String.slice method:

  1. start index - the index (zero-based) at which we start extraction
  2. end index - extract characters up to, but not including this index. A negative index of -1 means go up to, but not including the last character of the string
Passing an end index parameter of -1 and str.length - 1 is the same. We instruct the slice method to go up to, but not including the last character in the string.

The slice method does not mutate the original string, instead it returns a new string. Strings are immutable in JavaScript.

Calling the slice method on an empty string does not throw an error, it returns an empty string.

index.js
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 substring method.

index.js
const str = 'abcd'; const withoutFirstAndLast = str.substring(1, str.length - 1); console.log(withoutFirstAndLast); // ๐Ÿ‘‰๏ธ bc

In the example above, the String.substring method achieves the same result as the String.slice method.

The first parameter it takes is the start index (zero-based) and the second is the end index (up to, but not including).

If you pass a negative end index to the String.substring method 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 intuitive than String.substring in many scenarios.

An example of this confusing behavior is - if you pass a greater end index than start index to the String.substring method, it just reverses them, whereas the 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee