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

 var txt1 = "foo baz"

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

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


当前回答

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

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

简单的 Unicode编码点兼容

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

其他回答

您可以使用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!”

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

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

输出:

"something      "

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

以溶液为例。我用简单的格式写了这段代码:

const insertWord = (sentence,word,index) => {
    var sliceWord = word.slice(""),output = [],join; // Slicing the input word and declaring other variables
    var sliceSentence = sentence.slice(""); // Slicing the input sentence into each alphabets
    for (var i = 0; i < sliceSentence.length; i++) 
           {
        if (i === index) 
               { // checking if index of array === input index
            for (var j = 0; j < word.length; j++) 
                       {   // if yes we'll insert the word
                output.push(sliceWord[j]); // Condition is true we are inserting the word
                       }
            output.push(" "); // providing a single space at the end of the word
                 }
        output.push(sliceSentence[i]);  // pushing the remaining elements present in an array
            }
    join = output.join(""); // converting an array to string
    console.log(join)
    return join;
}

下面是我写的一个像所有其他编程语言一样的方法:

string .prototype.insert =函数(索引,字符串){ If (index > 0) { 返回。子字符串(0,index) +字符串+ this。substring(指数、this.length); } 返回string + this; }; //使用示例: var something =“你好吗?”; 某事=某事。插入(3,“are”); console.log(东西)

参考:

http://coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/

我知道这是一个古老的话题,然而,这里有一个真正有效的方法。

var tn = document.createTextNode("I am just  to help")
t.insertData(10, "trying");

这样做的好处在于它强制了节点内容。因此,如果该节点已经在DOM上,则不需要使用任何查询选择器或更新innerText。这些变化将反映由于其约束力。

如果需要字符串,只需访问节点的文本内容属性。

tn.textContent
#=> "I am just trying to help"