Remove the last Character from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 6, 2021

banner

Photo from Unsplash

Remove the last Character from a String #

To remove the last character from a string, call the slice() method, passing it 0 and -1 as parameters, e.g. str.slice(0, -1). The slice method extracts a section of the string and returns it as a new string, without modifying the original string.

index.js
const str = 'test'; const withoutLast = str.slice(0, -1); console.log(withoutLast); // 👉️ tes

The parameters we passed to the String.slice method are:

  1. start index - the index (zero-based) at which we begin extraction
  2. 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
Specifying an end index of -1 and str.length - 1 is the same. Either way, we instruct the slice method to go up to, but not including the last character.

Indexes are zero-based in JavaScript, so the index of the last element in the string is str.length - 1.

Note that the String.slice method does not mutate the original string, instead it returns a new string.

To achieve the same result, we can also use the String.substring method.

To remove the last character from a string, call the substring() method, passing it 0 and str.length - 1 as parameters. The substring method returns a new string containing the specified part of the original string.

index.js
const str = 'test'; const withoutLast = str.substring(0, str.length - 1); console.log(withoutLast); // 👉️ tes

In the code snippet, we use the substring method to create a copy of the original string, without the last character.

The substring method takes the start and end indexes as parameters and does not mutate the original string.

Note that if you pass a negative end index to the substring method it treats it as if you passed 0. This behavior is very confusing and is the reason I avoid using the substring method.

If you want to read more about the differences between the slice and substring 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.