Tue Oct 26 2021·1 min read
Photo by Artem Beliaikin
To remove the first 2 characters from a string, use the
2 as a parameter, e.g.
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.
in the string is
2 as the start index, we exclude the characters at position
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.
I'll send you 1 email a week with links to all of the articles I've written that week