Remove the Last 2 Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

banner

Photo by Jakub Chlouba

Remove the Last 2 Characters from a String #

To remove the last 2 characters from a string, call the slice() method, passing it 0 for the start index and -2 for the end index as parameters. The slice method will return a new string containing the extracted section of the original string.

index.js
const str = 'one two'; const removedLast2 = str.slice(0, -2); console.log(removedLast2); // ๐Ÿ‘‰๏ธ 'one t'
Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0, and the last - string.length - 1.

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

  1. start index - the index of the first character to be included in the new string.
  2. end index - extract characters up to, but not including this index. A negative index of -2 means go up to, but not including the last 2 characters of the string.
Passing an end index parameter of -2 and str.length - 2 is the same. We instruct the slice method to go up to, but not including the last 2 characters in the string.
index.js
const str = 'one two'; const removedLast2 = str.slice(0, -2); console.log(removedLast2); // ๐Ÿ‘‰๏ธ 'one t' // ๐Ÿ‘‡๏ธ same as above const removedLast2Again = str.slice(0, str.length - 2); console.log(removedLast2Again); // ๐Ÿ‘‰๏ธ 'one t'
The string.slice method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

An alternative, but also very common approach is to use the String.substring method.

To remove the last 2 characters from a string, call the substring() method on the string, passing it 0 for the start index and str.length - 1 for the end index as parameters. The substring method will return a new string without the last 2 characters of the original string.

index.js
const str = 'one two'; const removedLast2 = str.substring(0, str.length - 2); console.log(removedLast2); // ๐Ÿ‘‰๏ธ 'one t'

The parameters we passed to the substring method are the the start and end indexes.

The substring method doesn't handle negative indexes like slice does. If you pass a negative index to substring, it treats it as if you passed 0, which can be very confusing.

Another difference is that when the start index is greater than the end index, the substring method swaps them.

To read more about the differences between the slice and substring methods, check out this section of the MDN docs.

My personal preference is to use the slice method, because it works more intuitively and handles negative indexes in a manner one would expect.

Further Reading #

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