admin管理员组

文章数量:1129073

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;

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;
Share Improve this question edited May 19, 2019 at 9:31 John 13.7k14 gold badges109 silver badges189 bronze badges asked Dec 6, 2010 at 9:26 samisami 7,6458 gold badges36 silver badges37 bronze badges
Add a comment  | 

12 Answers 12

Reset to default 476

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


Optional: As a prototype method of String

The following can be used to splice text within another string at a desired index, with an optional removeCount parameter.

if (String.prototype.splice === undefined) {
  /**
   * Splices text within a string.
   * @param {int} offset The position to insert the text at (before)
   * @param {string} text The text to insert
   * @param {int} [removeCount=0] An optional number of characters to overwrite
   * @returns {string} A modified string containing the spliced text.
   */
  String.prototype.splice = function(offset, text, removeCount=0) {
    let calculatedOffset = offset < 0 ? this.length + offset : offset;
    return this.substring(0, calculatedOffset) +
      text + this.substring(calculatedOffset + removeCount);
  };
}

let originalText = "I want apple";

// Positive offset
console.log(originalText.splice(6, " an"));
// Negative index
console.log(originalText.splice(-5, "an "));
// Chaining
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }

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)

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

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'

try

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

var a = "I want apple";
var b = " an";
var position = 6;

var r= a.slice(0,position) + b + a.slice(position);

console.log(r);

or regexp solution

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

var a = "I want apple";
var b = " an";
var position = 6;

var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);

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

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.

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 Kiełczewski's, but without storing the initial characters in a capturing group):

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

var a = "I want apple";
var b = " an";
var position = 6;

var r= a.replace(new RegExp(`(?<=^.{${position}})`), b);

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

The Underscore.String library has a function that does Insert

insert(string, index, substring) => string

like so

insert("I want apple", 6, " an");
// => "I want an apple"
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)

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

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

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

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

With RegExp replace

var a = 'I want apple';
var b = ' an';
var position = 6;
var output = a.replace(new RegExp(`^(.{${position}})(.*)`), `$1${b}$2`);

console.log(output);

Info:

  • String.prototype.replace()
  • RegExp

本文标签: javascriptInserting string at position x of another stringStack Overflow