Remove the Last 3 Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20211 min read

Remove the Last 3 Characters from a String #

To remove the last 3 characters from a string, call the slice() method, passing it 0 and -3 as parameters, e.g. str.slice(0, -3). The slice method will return a new string containing the extracted section 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 last - string.length - 1.

We passed the following 2 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 -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 does not change the original string, it returns a new string. Strings are immutable in JavaScript.

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