Insert a string at a position within another string

I needed to insert a string within another string at a specific position. It is easy to retrieve the position of a string within another string. Here are two examples:

var string="Hello World";
var position = string.search("e");
alert(position);
position = string.indexOf("e");
alert(position);

Would both return:
1

I prefer using indexOf because it allows a start position and is quicker than using regex. Next, how do you insert: “i H” into this string. You can use substring, like this:

var result = string.substr(0, position) + "i H" + string.substr(position);

Which would return: “Hi Hello World”

I found a few great examples online for this, but I settled on the following using slice to cut up the string (array in the case of slice) and join to concatinate the array (string):

var result = [string.slice(0, position), "i H", string.slice(position)].join('');

Hope this helps!

Leave a Reply