Remove the First 2 Characters from a String in JavaScript


Borislav Hadzhiev

Last updated: Jul 27, 2022


Photo from Unsplash

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 argument 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 doesn't change the original string, it returns a new string. Strings are immutable in JavaScript.

JavaScript indexes are zero-based, 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 #

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.