[javascript] 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;

This question is related to javascript

The answer is


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

try

a.slice(0,position) + b + a.slice(position)

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.slice(0,position) + b + a.slice(position);_x000D_
_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

or regexp solution

"I want apple".replace(/^(.{6})/,"$1 an")

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);_x000D_
_x000D_
console.log(r);_x000D_
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
_x000D_
_x000D_
_x000D_


If ES2018's lookbehind is available, one more regexp solution, that makes use of it to "replace" at a zero-width position after the Nth character (similar to @Kamil Kielczewski's, but without storing the initial characters in a capturing group):

"I want apple".replace(/(?<=^.{6})/, " an")

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.replace(new RegExp(`(?<=^.{${position}})`), b);_x000D_
_x000D_
console.log(r);_x000D_
console.log("I want apple".replace(/(?<=^.{6})/, " an"));
_x000D_
_x000D_
_x000D_


Well just a small change 'cause the above solution outputs

"I want anapple"

instead of

"I want an apple"

To get the output as

"I want an apple"

use the following modified code

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

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

Edit: replaced .substr with .substring because .substr is now a legacy function (per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr)


Using ES6 string literals, would be much shorter:

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


var array = a.split(' '); 
array.splice(position, 0, b);
var output = array.join(' ');

This would be slower, but will take care of the addition of space before and after the an Also, you'll have to change the value of position ( to 2, it's more intuitive now)


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.


Quick fix! If you don't want to manually add a space, you can do this:

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

(edit: i see that this is actually answered above, sorry!)


The Underscore.String library has a function that does Insert

insert(string, index, substring) => string

like so

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