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

 var txt1 = "foo baz"

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

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


当前回答

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

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>!"

其他回答

正如许多人提到的,原型应该是最好的方法。确保原型出现的时间早于它被使用的时间。

String.prototype.insert = function (x, str) {
    return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};

使用切片

你可以使用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"]] ] ))

您可以使用regexp在一行代码中轻松完成这一任务

const str = 'Hello RegExp!'; Const index = 6; const insert = 'Lovely '; / /“你好RegExp !”.replace (/ ^ ({6 })(.)/, `$ 1的2美元的); const res = str.replace(新的正则表达式(^(。{${指数 }})(.)`), `$ 1 ${插入}$ 2 '); console.log (res);

“你好,可爱的RegExp!”

这基本上是@Base33所做的,除了我还提供了使用负号从末尾开始计数的选项。有点像substr方法所允许的。

// use a negative index to insert relative to the end of the string.

String.prototype.insert = function (index, string) {
  var ind = index < 0 ? this.length + index  :  index;
  return  this.substring(0, ind) + string + this.substr(ind);
};

例子: 假设您有使用命名约定的全尺寸图像,但不能更新数据以同时提供缩略图url。

var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');

//    result:  '/images/myimage_thm.jpg'

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

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

输出:

"something      "

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