Remove the First 2 Characters from a String in JavaScript


Borislav Hadzhiev

Tue Oct 26 20211 min read

Remove the First 2 Characters from a String #

To remove the first 2 characters from a string, use the slice method, passing it 2 as a parameter, e.g. str.slice(2). The slice method returns a new string containing the specified portion of the original string.

const str = 'test'; const withoutFirst2 = str.slice(2); console.log(withoutFirst2); // ๐Ÿ‘‰๏ธ 'st'

The only parameter we passed to the String.slice method is the start index - the index of the first character to be included in the new string.

The slice method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

Indexes are zero-based in JavaScript, meaning the index of the first character in the string is 0.

By specifying 2 as the start index, we exclude the characters at position 0 and 1.

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

const str = 'test'; // ๐Ÿ‘‡๏ธ using substring const withoutFirst2 = str.substring(2); console.log(withoutFirst2); // ๐Ÿ‘‰๏ธ 'st'

We achieved the same result by using the substring method. It also takes the start index as a parameter.

For our purposes the 2 methods do the same thing, however there are some differences between the 2. If you want to read more on that, check out this section from the MDN docs.

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