459

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.

1

20 Answers 20

586

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);
4
  • 5
    @AlejandroSalamancaMazuelo: substring would be fine here. I prefer slice in general because it's more flexible (negative indices, e.g. "foo baz".slice(1, -2)). It's also slightly shorter, for the little that's worth.
    – Tim Down
    Nov 9, 2015 at 16:36
  • 19
    Does ES6 offer a better alternative? Could at least use string interpolation, like `${txt1.slice(0,3)}bar${txt1.slice(3)}`
    – Jay
    Nov 17, 2015 at 18:54
  • 3
    This does not utilize the delete feature as included in the above; top answer... Nov 24, 2015 at 19:08
  • 19
    @Mr.Polywhirl: No. The question makes no mention of needing to do that.
    – Tim Down
    Nov 25, 2015 at 11:06
298

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

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

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"


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

5
  • 11
    I know this is from 2010, but the below slice solution is better and simpler. (Splice is destructive, slice isn't, and it's better to avoid modifying "objects you don't know"). This solution should absolutely not be the first visible answer, even though it may have made sense at the time. Aug 20, 2016 at 7:56
  • 7
    @EirikBirkeland: Strings are immutable. The above code doesn't modify any object. Either way, your notion of not modifying "objects you don't know" would preclude Array mutation methods. You saying you'd rather do my_array[my_array.length] = item instead of my_array.push(item)?
    – user1106925
    Sep 17, 2016 at 16:08
  • 5
    Sorry I meant "objects you don't OWN". You're right about splice in this case; indeed strings are immutable. For this reason I think splice is a poor key word choice though. My main objection is against extending prototypes arbitrarily, unless they're standard polyfills. Sep 19, 2016 at 13:54
  • 5
    It's incredibly bad practice to modify a built-in objects. As we saw with SmooshGate, this risks breaking your code as new functionality is added to the language and, should your irresponsible modification somehow gets into a library that sees significant uptake across the web, it could block the use of a simple, clear method name for new functionality.
    – Sean
    Jan 1, 2020 at 18:35
  • You can also actually use splice for inserting a string but it returns the removed elements and therefore requires multiple lines. It likely has bad performance (not as much as walking through single characters by RegEx though): const characters = [...originalString]; characters.splice(index, replaceCharCount, stringToInsert); const newString = characters.join("") Sep 22 at 11:25
160

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

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

  return string + this;
};

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

Reference:

2
  • 1
    You may need to add curly braces {} to the if-else blocks.
    – Mr-IDE
    May 29, 2018 at 11:43
  • 3
    No, don't need to. But the else is redundant.
    – Bitterblue
    Jul 16, 2018 at 10:16
91

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!

0
19

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"
3
  • 1
    This is also great if you need to insert text at multiple indices in a string. See my answer below if that's the case. Aug 15, 2014 at 15:27
  • There's no need to modify a built-in object's prototype like this. Bad form. Apr 13, 2022 at 13:38
  • Update for 2023, I would recommend positive lookbehind: originalString.replace( new RegExp( (?<=.{${ index }}), "su" ), stringToInsert ) It will automatically match at the start of the string, without a need for a start of string anchor. Why is such a very standard operation is still not available in Vanilla JS? Sep 22 at 10:47
19
  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

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

1
  • 1
    this is actually an incredibly simple solution I'd say the best option here, you can also probably inline it but fine as-is. Jun 2, 2021 at 15:36
19

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'
1
  • 2
    There's no need to modify a built-in object's prototype like this. Bad form. Apr 13, 2022 at 13:39
18

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>!"
4
  • 1
    I tried this method but replaced '6' and '11' with variables it doesn't work - what am I doing wrong - help please . Thanks in advance :)
    – Dex Dave
    May 12, 2015 at 18:35
  • 1
    6 and 11 are the indices at which the text will be inserted into the string. 6: "<span>" says: at index 6, insert the text "<span>". Are you saying that you want to use the value of an integer variable as the insertion index? If that's the case, try something like var a=6, text = {}; text[a] = "<span>"; May 12, 2015 at 20:37
  • 1
    yea I want to use integer variables as the insertion, your method worked - thanks you - this is what I used var a=6; var b=11; text = {}; text[a] = "xx";text[b] = "yy"; - is there a better way to write that though
    – Dex Dave
    May 12, 2015 at 21:30
  • There's no need to modify a built-in object's prototype like this. Bad form. Apr 13, 2022 at 13:40
10

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.

8
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/

7

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

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

"Hello Lovely RegExp!"

6

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"
6

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.

3
  • What does absIndex stans for?
    – enbermudas
    Jan 13, 2020 at 17:15
  • Btw, thanks for the second method. It works like a charm!
    – enbermudas
    Jan 13, 2020 at 17:29
  • There's no need to modify a built-in object's prototype like this. Bad form. Apr 13, 2022 at 13:40
4

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.

3

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);
3

Using slice

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

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

Splice method for Strings

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

String.prototype.splice = function(index,del,...newStrs){
  let str = this.split('');
  str.splice(index,del,newStrs.join('') || '');
  return str.join('');
}


 var txt1 = "foo baz"

//inserting single string.
console.log(txt1.splice(4,0,"bar ")); //foo bar baz


//inserting multiple strings
console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz


//removing letters
console.log(txt1.splice(1,2)) //f baz


//remving and inseting atm
console.log(txt1.splice(1,2," bar")) //f bar baz

Applying splice() at multiple indexes

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

String.prototype.splice = function(index,del,...newStrs){
  let str = this.split('');
  str.splice(index,del,newStrs.join('') || '');
  return str.join('');
}


String.prototype.mulSplice = function(arr){
  str = this
  let dif = 0;
  
  arr.forEach(x => {
    x[2] === x[2] || [];
    x[1] === x[1] || 0;
    str = str.splice(x[0] + dif,x[1],...x[2]);
    dif += x[2].join('').length - x[1];
  })
  return str;
}

let txt = "foo bar baz"

//Replacing the 'foo' and 'bar' with 'something1' ,'another'
console.log(txt.splice(0,3,'something'))
console.log(txt.mulSplice(
[
[0,3,["something1"]],
[4,3,["another"]]
]

))

1
  • There's no need to modify a built-in object's prototype like this. Bad form. Apr 13, 2022 at 13:40
1

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

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)

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

1
  • There's no need to modify a built-in object's prototype like this. Bad form. Apr 13, 2022 at 13:41
0

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;
}
0

Prototype should be the best approach as many mentioned. Make sure that prototype comes earlier than where it is used.

String.prototype.insert = function (x, str) {
    return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};
0

Still in 2023, it does not look like there is an insertion String method after looking at the inbuilt String methods in MDN's documentation.

There is a simple but wasteful one-liner that can do it and which wasn't mentioned yet.

Array.from(originalString, (c, i) => i == index ? insertString+c : c ).join("")

The advantage is obviously, that no additional variables are required. It can be used in expression-only-context.

(Note: negative indices are intensionally skipped, because they might have no valid meaning. -1 could have been produced by String.prototype.indexOf which actually means "no index".)

This one-liner inserts a string before the indexed character but you can easily modify it to insert after it or insert at a set of indices.

Array.from(originalString, (c, i) => indices?.includes?.(i) ? insertString+c : c ).join("")

This line is even slower of course. According to MDN, Sets can check faster for elements in average and therefore using them instead of arrays would speed things up.

Array.from(originalString, (c, i) => (indices?.has?.(i) ?? indices?.includes?.(i) ?? indices == i) ? insertString+c : c ).join("")

Finally, this one-liner replaces either a scalar (string or number), a set or an array of indices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.