[javascript] Insert a string at a specific index

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" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

This question is related to javascript string

The answer is


You could prototype your own splice() into String.

Polyfill

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

Example

_x000D_
_x000D_
String.prototype.splice = function(idx, rem, str) {_x000D_
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));_x000D_
};_x000D_
_x000D_
var result = "foo baz".splice(4, 0, "bar ");_x000D_
_x000D_
document.body.innerHTML = result; // "foo bar baz"
_x000D_
_x000D_
_x000D_


EDIT: Modified it to ensure that rem is an absolute value.


Take the solution. I have written this code in an easy format:

const insertWord = (sentence,word,index) => {
    var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
    var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
    for (var i = 0; i < sliceSentence.length; i++) 
           {
        if (i === index) 
               { // checking if index of array === input index
            for (var j = 0; j < word.length; j++) 
                       {   // if yes we'll insert the word
                output.push(sliceWord[j]); // Condition is true we are inserting the word
                       }
            output.push(" "); // providing a single space at the end of the word
                 }
        output.push(sliceSentence[i]);  // pushing the remaining elements present in an array
            }
    join = output.join(""); // converting an array to string
    console.log(join)
    return join;
}

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 <span> tags at certain offsets in a string:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"

Given your current example you could achieve the result by either

var txt2 = txt1.split(' ').join(' bar ')

or

var txt2 = txt1.replace(' ', ' bar ');

but given that you can make such assumptions, you might as well skip directly to Gullen's example.

In a situation where you really can't make any assumptions other than character index-based, then I really would go for a substring solution.


You can do it easily with regexp in one line of code

_x000D_
_x000D_
const str = 'Hello RegExp!';_x000D_
const index = 6;_x000D_
const insert = 'Lovely ';_x000D_
    _x000D_
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);_x000D_
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);_x000D_
    _x000D_
console.log(res);
_x000D_
_x000D_
_x000D_

"Hello Lovely RegExp!"


  1. Instantiate an array from the string
  2. Use Array#splice
  3. Stringify again using Array#join

The benefits of this approach are two-fold:

  1. Simple
  2. Unicode code point compliant

_x000D_
_x000D_
const pair = Array.from('USDGBP')_x000D_
pair.splice(3, 0, '/')_x000D_
console.log(pair.join(''))
_x000D_
_x000D_
_x000D_


my_string          = "hello world";
my_insert          = " dear";
my_insert_location = 5;

my_string = my_string.split('');  
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');

https://jsfiddle.net/gaby_de_wilde/wz69nw9k/


You can use Regular Expressions with a dynamic pattern.

var text = "something";
var output = "                    ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);

outputs:

"something      "

This replaces text.length of whitespace characters at the beginning of the string output. The RegExp means ^\ - beginning of a line \s any white space character, repeated {n} times, in this case text.length. Use \\ to \ escape backslashes when building this kind of patterns out of strings.


Inserting at a specific index (rather than, say, at the first space character) has to use string slicing/substring:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

This is basically doing what @Base33 is doing except I'm also giving the option of using a negative index to count from the end. Kind of like the substr method allows.

// use a negative index to insert relative to the end of the string.

String.prototype.insert = function (index, string) {
  var ind = index < 0 ? this.length + index  :  index;
  return  this.substring(0, ind) + string + this.substr(ind);
};

Example: Let's say you have full size images using a naming convention but can't update the data to also provide thumbnail urls.

var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');

//    result:  '/images/myimage_thm.jpg'

Just make the following function:

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

and then use it like that:

alert(insert("foo baz", 4, "bar "));

Output: foo bar baz

It behaves exactly, like the C# (Sharp) String.Insert(int startIndex, string value).

NOTE: This insert function inserts the string value (third parameter) before the specified integer index (second parameter) in the string str (first parameter), and then returns the new string without changing str!


another solution, cut the string in 2 and put a string in between.

var str = jQuery('#selector').text();

var strlength = str.length;

strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);

jQuery('#selector').html(strf + 'inserted' + strb);

UPDATE 2016: Here is another just-for-fun (but more serious!) prototype function based on one-liner RegExp approach (with prepend support on undefined or negative index):

/**
 * Insert `what` to string at position `index`.
 */
String.prototype.insert = function(what, index) {
    return index > 0
        ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
        : what + this;
};

console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"

Previous (back to 2012) just-for-fun solution:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

Well, we can use both the substring and slice method.

String.prototype.customSplice = function (index, absIndex, string) {
    return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};


String.prototype.replaceString = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substr(index);

    return string + this;
};


console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers

The only problem of a substring method is that it won't work with a negative index. It's always take string index from 0th position.


Here is a method I wrote that behaves like all other programming languages:

_x000D_
_x000D_
String.prototype.insert = function(index, string) {
  if (index > 0) {
    return this.substring(0, index) + string + this.substr(index);
  }

  return string + this;
};

//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
_x000D_
_x000D_
_x000D_

Reference:


I know this is an old thread, however, here is a really effective approach.

var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");

What's great about this is that it coerces the node content. So if this node were already on the DOM, you wouldn't need to use any query selectors or update the innerText. The changes would reflect due to its binding.

Were you to need a string, simply access the node's text content property.

tn.textContent
#=> "I am just trying to help"

I wanted to compare the method using substring and the method using slice from Base33 and user113716 respectively, to do that I wrote some code

also have a look at this performance comparison, substring, slice

The code I used creates huge strings and inserts the string "bar " multiple times into the huge string

_x000D_
_x000D_
if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function (start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

String.prototype.splice = function (idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};


String.prototype.insert = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);

    return string + this;
};


function createString(size) {
    var s = ""
    for (var i = 0; i < size; i++) {
        s += "Some String "
    }
    return s
}


function testSubStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.insert(4, "bar ")
}

function testSpliceStringPerformance(str, times) {
    for (var i = 0; i < times; i++)
        str.splice(4, 0, "bar ")
}


function doTests(repeatMax, sSizeMax) {
    n = 1000
    sSize = 1000
    for (var i = 1; i <= repeatMax; i++) {
        var repeatTimes = n * (10 * i)
        for (var j = 1; j <= sSizeMax; j++) {
            var actualStringSize = sSize *  (10 * j)
            var s1 = createString(actualStringSize)
            var s2 = createString(actualStringSize)
            var start = performance.now()
            testSubStringPerformance(s1, repeatTimes)
            var end = performance.now()
            var subStrPerf = end - start

            start = performance.now()
            testSpliceStringPerformance(s2, repeatTimes)
            end = performance.now()
            var splicePerf = end - start

            console.log(
                "string size           =", "Some String ".length * actualStringSize, "\n",
                "repeat count          = ", repeatTimes, "\n",
                "splice performance    = ", splicePerf, "\n",
                "substring performance = ", subStrPerf, "\n",
                "difference = ", splicePerf - subStrPerf  // + = splice is faster, - = subStr is faster
                )

        }
    }
}

doTests(1, 100)
_x000D_
_x000D_
_x000D_

The general difference in performance is marginal at best and both methods work just fine (even on strings of length ~~ 12000000)


Using slice

You can use slice(0,index) + str + slice(index). Or you can create a method for it.

_x000D_
_x000D_
String.prototype.insertAt = function(index,str){_x000D_
  return this.slice(0,index) + str + this.slice(index)_x000D_
}_x000D_
console.log("foo bar".insertAt(4,'baz ')) //foo baz bar
_x000D_
_x000D_
_x000D_

Splice method for Strings

You can split() the main string and add then use normal splice()

_x000D_
_x000D_
String.prototype.splice = function(index,del,...newStrs){_x000D_
  let str = this.split('');_x000D_
  str.splice(index,del,newStrs.join('') || '');_x000D_
  return str.join('');_x000D_
}_x000D_
_x000D_
_x000D_
 var txt1 = "foo baz"_x000D_
_x000D_
//inserting single string._x000D_
console.log(txt1.splice(4,0,"bar ")); //foo bar baz_x000D_
_x000D_
_x000D_
//inserting multiple strings_x000D_
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz_x000D_
_x000D_
_x000D_
//removing letters_x000D_
console.log(txt1.splice(1,2)) //f baz_x000D_
_x000D_
_x000D_
//remving and inseting atm_x000D_
console.log(txt1.splice(1,2," bar")) //f bar baz
_x000D_
_x000D_
_x000D_

Applying splice() at multiple indexes

The method takes an array of arrays each element of array representing a single splice().

_x000D_
_x000D_
String.prototype.splice = function(index,del,...newStrs){_x000D_
  let str = this.split('');_x000D_
  str.splice(index,del,newStrs.join('') || '');_x000D_
  return str.join('');_x000D_
}_x000D_
_x000D_
_x000D_
String.prototype.mulSplice = function(arr){_x000D_
  str = this_x000D_
  let dif = 0;_x000D_
  _x000D_
  arr.forEach(x => {_x000D_
    x[2] === x[2] || [];_x000D_
    x[1] === x[1] || 0;_x000D_
    str = str.splice(x[0] + dif,x[1],...x[2]);_x000D_
    dif += x[2].join('').length - x[1];_x000D_
  })_x000D_
  return str;_x000D_
}_x000D_
_x000D_
let txt = "foo bar baz"_x000D_
_x000D_
//Replacing the 'foo' and 'bar' with 'something1' ,'another'_x000D_
console.log(txt.splice(0,3,'something'))_x000D_
console.log(txt.mulSplice(_x000D_
[_x000D_
[0,3,["something1"]],_x000D_
[4,3,["another"]]_x000D_
]_x000D_
_x000D_
))
_x000D_
_x000D_
_x000D_