Remove the Last 3 Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Remove the Last 3 Characters from a String #

Use the String.slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str.slice(0, -3);. The slice method will return a new string that doesn't contain the last 3 characters of the original string.

index.js
const str = 'hello!!!'; const withoutLast3 = str.slice(0, -3); console.log(withoutLast3); // 👉️ 'hello'
Indexes are zero-based in JavaScript, meaning the index of the first character in a string is 0, and the index of the last is string.length - 1.

We passed the following 2 arguments 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 -3 means go up to, but not including the last 3 characters of the string.
Passing an end index parameter of -3 and str.length - 3 is the same. We instruct the slice method to go up to, but not including the last 3 characters in the string.
index.js
const str = 'hello!!!'; const withoutLast3 = str.slice(0, -3); console.log(withoutLast3); // 👉️ 'hello' // 👇️ same as above const withoutLast3Again = str.slice(0, str.length - 3); console.log(withoutLast3Again); // 👉️ 'hello'
The String.slice() method doesn't 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.

Use the String.substring() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str.substring(0, str.length - 3);. The substring method will return a new string that doesn't contain the last 3 characters of the original string.

index.js
const str = 'hello!!!'; const withoutLast3 = str.substring(0, str.length - 3); console.log(withoutLast3); // 👉️ 'hello'

The parameters we passed to the substring method are 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 between the two methods 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 #

Use the search field on my Home Page to filter through my more than 3,000 articles.