Insert a string at a specific index

JavascriptString

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.substr(index);
  }

  return string + this;
};

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

Reference:

Solution 4 - Javascript

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!

Solution 5 - Javascript

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"

Solution 6 - Javascript

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'

Solution 7 - Javascript

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

Solution 8 - Javascript

  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(''))

Solution 9 - Javascript

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.

Solution 10 - Javascript

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/

Solution 11 - Javascript

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"

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

Solution 14 - Javascript

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.

Solution 15 - Javascript

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

Solution 16 - Javascript

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

))

Solution 17 - Javascript

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)

Solution 18 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJiew MengView Question on Stackoverflow
Solution 1 - JavascriptTim DownView Answer on Stackoverflow
Solution 2 - Javascriptuser113716View Answer on Stackoverflow
Solution 3 - JavascriptBase33View Answer on Stackoverflow
Solution 4 - Javascriptuser2133061View Answer on Stackoverflow
Solution 5 - JavascriptVisioNView Answer on Stackoverflow
Solution 6 - JavascriptRyan OreView Answer on Stackoverflow
Solution 7 - JavascriptJake StoefflerView Answer on Stackoverflow
Solution 8 - JavascriptBen AstonView Answer on Stackoverflow
Solution 9 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 10 - Javascriptuser40521View Answer on Stackoverflow
Solution 11 - JavascriptSebastian SchollView Answer on Stackoverflow
Solution 12 - JavascriptkamalView Answer on Stackoverflow
Solution 13 - JavascriptMadmadiView Answer on Stackoverflow
Solution 14 - JavascriptInoperableView Answer on Stackoverflow
Solution 15 - Javascriptmudshark2005View Answer on Stackoverflow
Solution 16 - JavascriptMaheer AliView Answer on Stackoverflow
Solution 17 - JavascriptPierreView Answer on Stackoverflow
Solution 18 - JavascriptMd Bilal ZafarView Answer on Stackoverflow