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

 var txt1 = "foo baz"

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

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


当前回答

另一种解决办法是,把绳子切成两半,在中间放一根绳子。

var str = jQuery('#selector').text();

var strlength = str.length;

strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);

jQuery('#selector').html(strf + 'inserted' + strb);

其他回答

我们可以同时使用子字符串和切片方法。

String.prototype.customSplice = function (index, absIndex, string) {
    return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};


String.prototype.replaceString = function (index, string) {
    if (index > 0)
        return this.substring(0, index) + string + this.substr(index);

    return string + this;
};


console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers

子字符串方法的唯一问题是它不能与负索引一起工作。它总是从第0位开始取字符串下标。

使用切片

你可以使用slice(0,index) + str + slice(index)。或者您可以为它创建一个方法。

String.prototype.insertAt =函数(索引,str){ 返回this.slice(0,index) + STR + this.slice(index) } console.log (" foo栏”。insertAt(4,'baz ')) //foo baz bar

字符串的拼接方法

你可以split()主字符串并添加,然后使用普通的splice()

String.prototype.splice = function(index,del,...newStrs){ let str = this.split(''); str.splice(index,del,newStrs.join('') || ''); return str.join(''); } var txt1 = "foo baz" //inserting single string. console.log(txt1.splice(4,0,"bar ")); //foo bar baz //inserting multiple strings console.log(txt1.splice(4,0,"bar ","bar2 ")); //foo bar bar2 baz //removing letters console.log(txt1.splice(1,2)) //f baz //remving and inseting atm console.log(txt1.splice(1,2," bar")) //f bar baz

在多个索引上应用splice()

该方法接受一个数组,数组中的每个元素表示一个splice()。

String.prototype.splice = function(index,del,...newStrs){ let str = this.split(''); str.splice(index,del,newStrs.join('') || ''); return str.join(''); } String.prototype.mulSplice = function(arr){ str = this let dif = 0; arr.forEach(x => { x[2] === x[2] || []; x[1] === x[1] || 0; str = str.splice(x[0] + dif,x[1],...x[2]); dif += x[2].join('').length - x[1]; }) return str; } let txt = "foo bar baz" //Replacing the 'foo' and 'bar' with 'something1' ,'another' console.log(txt.splice(0,3,'something')) console.log(txt.mulSplice( [ [0,3,["something1"]], [4,3,["another"]] ] ))

在特定索引处插入(而不是在第一个空格字符处)必须使用字符串切片/子字符串:

var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);

更新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"

您可以将正则表达式与动态模式一起使用。

var text = "something";
var output = "                    ";
var pattern = new RegExp("^\\s{"+text.length+"}");
var output.replace(pattern,text);

输出:

"something      "

这将替换文本。字符串输出开头的空白字符的长度。 RegExp表示^\ -行首任意空格字符,重复{n}次,在本例中为text.length。在用字符串构建这种模式时,使用\\来转义反斜杠。