Categories
JavaScript Answers

How to Insert a JavaScript Substring at a Specific Index of an Existing String?

Spread the love

Sometimes, we may want to insert a JavaScript substring at a specific index of an existing string.

In this article, we’ll look at how to insert a JavaScript substring at a specific index of an existing string.

String.prototype.slice

We can call slice on a string with the start and end indexes to extract a substring from the start index to the end index minus 1.

So we can use it to break the existing string into 2 substrings with the index that we want to insert the substring to.

And we can put the substring in between the 2 broken substrings.

For instance, we can write:

const txt1 = 'foobaz'  
const txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);  
console.log(txt2)

We have txt1 set to 'foobar' .

And we want to insert 'baz' between 'foo' and 'baz' .

To do this, we call slice with start index 0 and end index 3 to extract the segment between index 0 and 2.

And we call slice again to extract the substring from index 3 to the end of the string.

Then we concatenate the strings together with + .

So we get 'foobarbaz’ as a result.

String.prototype.substring

We can replace the slice method with the substring method.

It takes the same arguments as slice .

So we can write:

const txt1 = 'foobaz'  
const txt2 = txt1.substring(0, 3) + "bar" + txt1.substring(3);  
console.log(txt2)

And we get the same value for txt2 .

Conclusion

We can insert a substring into an existing at the existing index with the JavaScript string’s slice or substring methods.

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 *