Remove the first N characters from a String in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 06 20212 min read

banner

Photo by Emma Francis

Remove the first N characters from a String #

To remove the first n characters from a string:

  1. Call the substring method, passing it the number of characters to be removed as a parameter.
  2. For example, str.substring(2) returns a new string with the first two characters of the original string removed.
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

In the code snippet we pass 2 as a starting index to the String.substring method.

Indexes are zero-based in JavaScript, which means that the first character of the 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 index 0 and 1 and include the rest into the new string.

In the second example we have 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 the characters from index 5 to index 7.

Note that the substring method does not mutate the original string, it returns a brand new string. Strings are immutable in JavaScript.

An alternative, but very similar approach is to use the slice method.

To remove the first n characters of a string, call the slice method, passing it the number of characters to be removed as a parameter, e.g. str.slice(2). The slice method returns a new string containing the extracted section of the 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

In the code snippet, we use the String.slice method to achieve the same result as with the String.substring method.

The method takes the same parameters - 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.

It's a matter of personal preference, however I prefer the slice method over substring. The slice method is more flexible and intuitive than the substring method for some use cases mentioned in the MDN docs.

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