Inserting string at position x of another string

Inserting string at position x of another string

I have two variables and need to insert string b into string a at the point represented by position. The result I’m looking for is “I want an apple”. How can I do this with JavaScript?
var a = ‘I want apple’;
var b = ‘ an’;
var position = 6;


Solution 1:

var a = "I want apple";
var b = "an";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');

Solution 2:

var output = a.substring(0, position) + b + a.substring(position);

Edit: replaced .substr with .substring because .substr is now a legacy function (per

Solution 3:

You can add this function to string class

String.prototype.insert_at=function(index, string)
  return this.substr(0, index) + string + this.substr(index);

so that you can use it on any string object:

var my_string = "abcd";
my_string.insertAt(1, "XX");

Solution 4:

Maybe it’s even better if you determine position using indexOf() like this:

function insertString(a, b, at)
    var position = a.indexOf(at); 

    if (position !== -1)
        return a.substr(0, position) + b + a.substr(position);    

    return "substring not found";

then call the function like this:

insertString("I want apple", "an ", "apple");

Note, that I put a space after the “an ” in the function call, rather than in the return statement.

Related:  Typescript import/as vs import/require? [duplicate]

Solution 5:

The Underscore.String library has a function that does Insert

insert(string, index, substring) => string

like so

insert("Hello ", 6, "world");
// => "Hello world"

Solution 6:

Using ES6 string literals, would be much shorter:

const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'