How can I insert a string at a specific index of another string?
var txt1 = \"foo baz\"
Suppose I want to insert \"bar \" after the \"foo
If anyone is looking for a way to insert text at multiple indices in a string, try this out:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
For example, you can use this to insert tags at certain offsets in a string:
var text = {
6: "",
11: ""
};
"Hello world!".insertTextAtIndices(text); // returns "Hello world!"