Categories
JavaScript Answers

How to remove chars between indexes in a JavaScript string?

Spread the love

Sometimes, we want to remove chars between indexes in a JavaScript string.

In this article, we’ll look at how to remove chars between indexes in a JavaScript string.

How to remove chars between indexes in a JavaScript string?

To remove chars between indexes in a JavaScript string, we can use the JavaScript string substr method.

For instance, we write:

const s = "hi how are you";
const startIndex = 2;
const endIndex = 6;
const newS = s.substr(0, startIndex) + s.substr(endIndex);
console.log(newS)

We want to remove the characters of s between startIndex and endIndex exclusive.

To do this, we call substr with 0 and startIndex to get the part of s between index 0 and startIndex - 1.

And then we call substr again with endIndex to return the part of s between endIndex and the end of the s.

Finally, we concatenate them together and assign it to newS.

Therefore, newS is 'hi are you'.

Conclusion

To remove chars between indexes in a JavaScript string, we can use the JavaScript string substr method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *