Remove First and Last Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

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, 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

We used the String.substring method to achieve the same result.

The first parameter the method 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 different scenarios.

An example of this confusing behavior is that 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 two methods, check out this section in the MDN docs.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.