Wed Oct 06 2021·2 min read
Photo by Emma Francis
To remove the first n characters from a string:
substringmethod, passing it the number of characters to be removed as a parameter.
str.substring(2)returns a new string with the first two characters of the original string removed.
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
2 as an argument to the
substring method, we specify that we want
to omit the characters at index
1 and include the rest into the new
In the second example we have passed 2 arguments to the
substring method returns the characters up to but not including the end
index. In our case the characters from index
5 to index
An alternative, but very similar approach is to use the
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.
slice method returns a new string containing the extracted section of the
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
method to achieve the same result as with the
The method takes the same parameters - the start and end indexes.
Note that there are some differences between the
methods, for more details, check out this section of the
slicemethod is more flexible and intuitive than the
substringmethod for some use cases mentioned in the MDN docs.
I'll send you 1 email a week with links to all of the articles I've written that week