Remove the first N characters from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Check out my new book

Remove the first N characters from a String #

Use the String.substring() method to remove the first N characters from a string, e.g. const result = str.substring(N). The substring method will return a new string that doesn't contain the first N characters of the original string.

index.js
const str = 'Hello world'; const firstTwo = str.substring(2); console.log(firstTwo); // 👉️ llo world const middle = str.substring(5, 8); console.log(middle); // 👉️ wo

We passed 2 as a starting index to the String.substring method.

JavaScript indexes are zero-based, meaning the first character in a string has an index of 0.

By passing 2 as an argument to the substring method, we specify that we want to omit the characters at indexes 0 and 1 and get a new string containing the rest.

In the second example, we passed 2 arguments to the String.substring method:

  • the start index - the index of the first character to include in the new string
  • the end index - the index of the first character to exclude from the new string

The substring method returns the characters up to but not including the end index. In our case, it returns the characters from index 5 to index 7.

Note that the substring method doesn't mutate the original string, it returns a new string. Strings are immutable in JavaScript.

Alternatively, you can use the slice() method.

Use the String.slice() method to remove the first N characters from a string, e.g. const result = str.slice(N). The slice method will return a new string that doesn't contain the first N characters of the original string.

index.js
const str = 'Hello world'; const firstTwo = str.slice(2); console.log(firstTwo); // 👉️ llo world const middle = str.slice(5, 8); console.log(middle); // 👉️ wo

We used the String.slice method to remove the first N characters from a string.

The method takes the same parameters as the substring method - the start and end indexes.

Note that there are some differences between the slice and substring methods. For more details, check out this section of the MDN docs.

Which approach you pick is a matter of personal preference. I'd go with the slice method as I find it more intuitive in some other scenarios that are covered 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.