Insert a string at a specific index

Solution 1:

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:

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:

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:

  • http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/

Solution 4:

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!