代码之家  ›  专栏  ›  技术社区  ›  Jiew Meng

在特定索引处插入字符串

  •  264
  • Jiew Meng  · 技术社区  · 15 年前

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

     var txt1 = "foo baz"
    

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

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

    17 回复  |  直到 6 年前
        1
  •  225
  •   Mr. Polywhirl    10 年前

    你可以自己制作原型 splice() 变为字符串。

    多段填充

    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));
    };
    
    var result = "foo baz".splice(4, 0, "bar ");
    
    document.body.innerHTML = result; // "foo bar baz"

    编辑: 修改它以确保 rem 是绝对值。

        2
  •  328
  •   Tim Down    15 年前

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

    var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
    
        3
  •  124
  •   Base33    6 年前

    试试这个。 这是我编写的一个方法,它的行为与所有其他编程语言一样。

    String.prototype.insert = function (index, string) {
      if (index > 0)
        return this.substring(0, index) + string + this.substring(index, this.length);
    
      return string + this;
    };
    

    使用示例:

    var something = "How you?";
    something = something.insert(3, " are");
    

    简单。

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

        4
  •  57
  •   user2133061    11 年前

    只需执行以下功能:

    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.insert(int startindex,string value)完全相同。

    注: 此插入函数插入字符串 价值 (第三个参数) 之前 指定的整数 指数 (第二个参数)在字符串中 STR (第一个参数),然后返回新字符串而不更改 STR !

        5
  •  15
  •   VisioN    9 年前

    2016年更新: 这是另一个 只是为了好玩 (但更严重!)基于一条直线的原型函数 RegExp 进近(预端支援开启 undefined 或负 index ):

    /**
     * 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"
    
        6
  •  10
  •   Jake Stoeffler    10 年前

    如果有人想在字符串中的多个索引处插入文本,请尝试以下操作:

    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>!"
    
        7
  •  9
  •   Ryan Ore    11 年前

    这基本上就是在做@bass33所做的,除了我还提供了使用负索引从结尾开始计数的选项。有点像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.substring(ind, this.length);
    };
    

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

    var url = '/images/myimage.jpg';
    var thumb = url.insert(-4, '_thm');
    
    //    result:  '/images/myimage_thm.jpg'
    
        8
  •  8
  •   user40521    9 年前
    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/

        9
  •  7
  •   David Hedlund    15 年前

    根据您当前的示例,您可以通过

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

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

    但是考虑到你可以做出这样的假设,你也可以直接跳过古伦的例子。

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

        10
  •  5
  •   Quelklef    10 年前
    function insertString(string, insertion, place) {
      return string.replace(string[place] + string[place + 1], string[place] + insertion + string[place + 1])
    }
    

    所以,对你来说 insertString("foo baz", "bar", 3);

    显然,这将是一个要使用的油漆,因为每次都必须向函数提供字符串,但目前我不知道如何使它变得更简单,如 string.replace(insertion, place) . 不过,这个想法仍然有效。

        11
  •  4
  •   Inoperable    12 年前

    可以将正则表达式与 动态 模式。

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

    输出:

    "something      "
    

    这将取代 text.length 字符串开头的空白字符数 output . 这个 RegExp 方法 ^\ -行首 \s 任何空白字符,重复 {n} 次,在这种情况下 文本长度 . 使用 \\ \ 当用字符串构建这种模式时,要避免反斜杠。

        12
  •  4
  •   Sebastian Scholl    7 年前

    我知道这是一条老路,但是,这里有一个非常有效的方法。

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

    最重要的是它强制节点内容。因此,如果此节点已经在DOM上,则不需要使用任何查询选择器或更新InnerText。由于其具有约束力,这些变化将反映出来。

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

    tn.textContent
    #=> "I am just trying to help"
    
        13
  •  3
  •   mudshark2005    12 年前

    另一个解决方案是,将字符串切割为2,并在中间放置一个字符串。

    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);
    
        14
  •  3
  •   Kamal Kant    6 年前

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

    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.substring(index, this.length);
    
        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个位置获取字符串索引。

        15
  •  1
  •   Maheer Ali    6 年前

    使用切片

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

    String.prototype.insertAt = function(index,str){
      return this.slice(0,index) + str + this.slice(index)
    }
    console.log("foo bar".insertAt(4,'baz ')) //foo baz bar

    串的拼接方法

    你可以 split() 主字符串和Add,然后使用Normal 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()。

    该方法获取一个数组,每个数组元素表示一个 拼接() .

    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"]]
    ]
    
    ))
        16
  •  1
  •   Pierre    6 年前

    我想比较使用子字符串的方法和分别使用base33和user113716的slice的方法,为此我编写了一些代码

    也可以看看这个 performance comparison, substring, slice

    我使用的代码创建了巨大的字符串,并将字符串“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的字符串上也是如此)。

        17
  •  1
  •   Madmadi    6 年前

    在一行代码中使用regexp可以很容易地做到这一点

    const str = 'Hello RegExp!';
    const index = 6;
    const insert = 'Lovely ';
    
    //'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
    str.replace(new RegExp(`^(.{${ index }})(.)`), `$1${ insert }$2`);
    
    //< "Hello Lovely RegExp!"