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

 var txt1 = "foo baz"

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

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


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

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

or

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

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

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


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

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

您可以将自己的splice()原型化为String。

Polyfill

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

例子

String.prototype.splice = function(idx, rem, str) { 返回 this.slice(0, idx) + str + this.slice(idx + Math.abs(rem)); }; var result = “foo baz”.splice(4, 0, “bar ”); document.body.innerHTML = result;“嘟”


EDIT:修改它,以确保rem是一个绝对值。


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

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/


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

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

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

输出:

"something      "

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


只需制作如下函数:

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!


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

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

这基本上是@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'

my_string          = "hello world";
my_insert          = " dear";
my_insert_location = 5;

my_string = my_string.split('');  
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');

https://jsfiddle.net/gaby_de_wilde/wz69nw9k/


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

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

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

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

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

使用切片

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


我想比较使用substring的方法和使用slice的方法分别来自Base33和user113716,为此我写了一些代码

还可以看看这个性能比较,子字符串,切片

我使用的代码创建了巨大的字符串,并将字符串“bar”多次插入到巨大的字符串中

if (!String.prototype.splice) { /** * {JSDoc} * * The splice() method changes the content of a string by removing a range of * characters and/or adding new characters. * * @this {String} * @param {number} start Index at which to start changing the string. * @param {number} delCount An integer indicating the number of old chars to remove. * @param {string} newSubStr The String that is spliced in. * @return {string} A new string with the spliced substring. */ String.prototype.splice = function (start, delCount, newSubStr) { return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount)); }; } String.prototype.splice = function (idx, rem, str) { return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem)); }; String.prototype.insert = function (index, string) { if (index > 0) return this.substring(0, index) + string + this.substring(index, this.length); return string + this; }; function createString(size) { var s = "" for (var i = 0; i < size; i++) { s += "Some String " } return s } function testSubStringPerformance(str, times) { for (var i = 0; i < times; i++) str.insert(4, "bar ") } function testSpliceStringPerformance(str, times) { for (var i = 0; i < times; i++) str.splice(4, 0, "bar ") } function doTests(repeatMax, sSizeMax) { n = 1000 sSize = 1000 for (var i = 1; i <= repeatMax; i++) { var repeatTimes = n * (10 * i) for (var j = 1; j <= sSizeMax; j++) { var actualStringSize = sSize * (10 * j) var s1 = createString(actualStringSize) var s2 = createString(actualStringSize) var start = performance.now() testSubStringPerformance(s1, repeatTimes) var end = performance.now() var subStrPerf = end - start start = performance.now() testSpliceStringPerformance(s2, repeatTimes) end = performance.now() var splicePerf = end - start console.log( "string size =", "Some String ".length * actualStringSize, "\n", "repeat count = ", repeatTimes, "\n", "splice performance = ", splicePerf, "\n", "substring performance = ", subStrPerf, "\n", "difference = ", splicePerf - subStrPerf // + = splice is faster, - = subStr is faster ) } } } doTests(1, 100)

性能上的一般差异充其量是边际的,两种方法都工作得很好(即使在长度~~ 12000000的字符串上)


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

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位开始取字符串下标。


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


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

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

简单的 Unicode编码点兼容

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


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

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 = function (x, str) {
    return (x > 0) ? this.substring(0, x) + str + this.substr(x) : str + this;
};