Last updated: Jul 27, 2022
Photo from Unsplash
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 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 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.