在另一个字符串的位置x处插入字符串

时间:2010-12-06 09:26:06

标签: javascript

我有两个变量,需要在b表示的点处将字符串a插入字符串position。我正在寻找的结果是“我想要一个苹果”。我怎么能用JavaScript做到这一点?

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

11 个答案:

答案 0 :(得分:323)

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

答案 1 :(得分:215)

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

答案 2 :(得分:28)

您可以将此功能添加到字符串类

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

以便您可以在任何字符串对象上使用它:

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

答案 3 :(得分:8)

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.

答案 4 :(得分:4)

Underscore.String库具有执行Insert

的功能
  

insert(string,index,substring)=>串

喜欢这样

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

答案 5 :(得分:4)

如果ES2018的后缀为available,这是另一种正则表达式解决方案,它将使用它在第N个字符后的零宽位置处“替换”(类似于@KamilKiełczewski的,但不将初始字符存储在捕获组中)

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

答案 6 :(得分:2)

使用 ES6字符串文字会更短:

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'

答案 7 :(得分:1)

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

这会慢一些,但是会在a之前和之后添加空间 此外,你必须改变位置的值(到2,它现在更直观)

答案 8 :(得分:0)

只是一个小小的变化'因为上面的解决方案输出

  

“我想要一个苹果”

而不是

  

“我想要一个苹果”

将输出设为

  

“我想要一个苹果”

使用以下修改后的代码

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

答案 9 :(得分:0)

快速修复!如果您不想手动添加空格,可以执行以下操作:

reloadData()

(编辑:我看到上面已经回答了,对不起!)

答案 10 :(得分:0)

尝试

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

或正则表达式解决方案

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

相关问题