如何在另一个字符串的特定索引处插入一个字符串?

 var txt1 = "foo baz"

假设我想在“foo”之后插入“bar”,我该如何实现呢?

我想到了substring(),但一定有一个更简单更直接的方法。


当前回答

更新2016:下面是另一个基于一行RegExp方法的原型函数(在未定义或负索引上提供prepend支持):

/**
 * Insert `what` to string at position `index`.
 */
String.prototype.insert = function(what, index) {
    return index > 0
        ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
        : what + this;
};

console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"

之前(回到2012年)只是为了好玩的解决方案:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

其他回答

只需制作如下函数:

function insert(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

然后像这样使用:

alert(insert("foo baz", 4, "bar "));

输出:foo bar baz

它的行为完全像c# (Sharp) String。插入(int startIndex,字符串值)。

注意:这个insert函数将字符串值(第三个参数)插入到字符串str(第一个参数)中指定的整型索引(第二个参数)之前,然后返回新的字符串而不改变str!

对于你当前的例子,你可以用任何一种方法来达到这个结果

var txt2 = txt1.split(' ').join(' bar ')

or

var txt2 = txt1.replace(' ', ' bar ');

但既然你可以做出这样的假设,你不妨直接跳过葛伦的例子。

在这种情况下,除了基于字符索引之外,您真的不能做出任何假设,那么我真的会选择子字符串解决方案。

更新2016:下面是另一个基于一行RegExp方法的原型函数(在未定义或负索引上提供prepend支持):

/**
 * Insert `what` to string at position `index`.
 */
String.prototype.insert = function(what, index) {
    return index > 0
        ? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
        : what + this;
};

console.log( 'foo baz'.insert('bar ', 4) );  // "foo bar baz"
console.log( 'foo baz'.insert('bar ')    );  // "bar foo baz"

之前(回到2012年)只是为了好玩的解决方案:

var index = 4,
    what  = 'bar ';

'foo baz'.replace(/./g, function(v, i) {
    return i === index - 1 ? v + what : v;
});  // "foo bar baz"

从字符串实例化一个数组 使用数组#拼接 再次使用array# join进行Stringify

这种方法的好处有两方面:

简单的 Unicode编码点兼容

const pair = Array.from('USDGBP') 对。Splice (3,0, '/') console.log (pair.join ("))

如果有人正在寻找一种在字符串的多个下标处插入文本的方法,请尝试以下方法:

String.prototype.insertTextAtIndices = function(text) {
    return this.replace(/./g, function(character, index) {
        return text[index] ? text[index] + character : character;
    });
};

例如,你可以使用它在字符串的特定偏移处插入<span>标签:

var text = {
    6: "<span>",
    11: "</span>"
};

"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"