【问题标题】:Inserting string at position x of another string在另一个字符串的位置 x 插入字符串
【发布时间】:2011-05-20 21:01:41
【问题描述】:

我有两个变量,需要将字符串b 插入到字符串a 中由position 表示的点。我正在寻找的结果是“我想要一个苹果”。如何使用 JavaScript 做到这一点?

var a = 'I want apple';
var b = ' an';
var position = 6;

【问题讨论】:

    标签: javascript


    【解决方案1】:

    RegExp替换

    var a = 'I want apple';
    var b = ' an';
    var position = 6;
    var output = a.replace(new RegExp(`^(.{${position}})(.*)`), `$1${b}$2`);
    
    console.log(output);

    信息:

    【讨论】:

      【解决方案2】:

      var a = "I want apple";
      var b = " an";
      var position = 6;
      var output = [a.slice(0, position), b, a.slice(position)].join('');
      console.log(output);

      可选:作为String的原型方法

      以下可用于将text 拼接到另一个字符串中所需的index,并带有可选的removeCount 参数。

      if (String.prototype.splice === undefined) {
        /**
         * Splices text within a string.
         * @param {int} offset The position to insert the text at (before)
         * @param {string} text The text to insert
         * @param {int} [removeCount=0] An optional number of characters to overwrite
         * @returns {string} A modified string containing the spliced text.
         */
        String.prototype.splice = function(offset, text, removeCount=0) {
          let calculatedOffset = offset < 0 ? this.length + offset : offset;
          return this.substring(0, calculatedOffset) +
            text + this.substring(calculatedOffset + removeCount);
        };
      }
      
      let originalText = "I want apple";
      
      // Positive offset
      console.log(originalText.splice(6, " an"));
      // Negative index
      console.log(originalText.splice(-5, "an "));
      // Chaining
      console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
      .as-console-wrapper { top: 0; max-height: 100% !important; }

      【讨论】:

      • 对于长字符串,这个解决方案比nickf的解决方案更快(因为它复制的更少)。
      • 这个解决方案并不快。我对此很好奇并运行了一个jsperf。这是给将来阅读此内容的任何人的说明。 jsperf.com/javascript-string-splice。在最新的 FF/Chrome/IE10/IE9 中测试。为了清晰度和性能,我会使用精益 nickf 的方法。
      • 嗯,这很有可能。这里的答案已经有将近 3 年的历史了,当时的大多数浏览器和版本确实使用 Array 连接(尤其是 IE)执行得更快。
      • 请您原谅我重新提出了这样一个老问题,但对于我来说值得var output = [a.slice(0, position + 1), b, a.slice(position)].join(''); 给操作人员“我想要一个苹果”,而不是“我想要一个苹果” "。
      • @PaulVon 纠正一些事情永远不会错,所以不需要原谅。反正我有点不同意。功能上做了它打算做的事情,在另一个字符串中的某个位置插入一个字符串。实际上插入的字符串应该像“an”,在这种情况下会更正确。
      【解决方案3】:

      如果 ES2018 的后视是 available,这是另一种正则表达式解决方案,它利用它在第 N 个字符之后的 零宽度位置“替换”(类似于 @Kamil Kiełczewski,但不将初始字符存储在捕获组中):

      "I want apple".replace(/(?<=^.{6})/, " an")
      

      var a = "I want apple";
      var b = " an";
      var position = 6;
      
      var r= a.replace(new RegExp(`(?<=^.{${position}})`), b);
      
      console.log(r);
      console.log("I want apple".replace(/(?<=^.{6})/, " an"));

      【讨论】:

        【解决方案4】:
        var output = a.substring(0, position) + b + a.substring(position);
        

        编辑:将 .substr 替换为 .substring,因为 .substr 现在是旧功能(根据 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

        【讨论】:

        【解决方案5】:

        您可以将此函数添加到字符串类中

        String.prototype.insert_at=function(index, string)
        {   
          return this.substr(0, index) + string + this.substr(index);
        }
        

        这样你就可以在任何字符串对象上使用它:

        var my_string = "abcd";
        my_string.insertAt(1, "XX");
        

        【讨论】:

        • 修改原生对象原型是一种不好的做法:stackoverflow.com/questions/14034180/…
        • -1: 不修改原始变量并且您在第二个示例中错误地使用了camelCase 而不是underscore_case
        【解决方案6】:

        使用 ES6 字符串文字,会更短:

        const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
            
        console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'

        【讨论】:

          【解决方案7】:

          试试

          a.slice(0,position) + b + a.slice(position)
          

          var a = "I want apple";
          var b = " an";
          var position = 6;
          
          var r= a.slice(0,position) + b + a.slice(position);
          
          console.log(r);

          或正则表达式解决方案

          "I want apple".replace(/^(.{6})/,"$1 an")
          

          var a = "I want apple";
          var b = " an";
          var position = 6;
          
          var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);
          
          console.log(r);
          console.log("I want apple".replace(/^(.{6})/,"$1 an"));

          【讨论】:

            【解决方案8】:

            快速修复!如果不想手动添加空格,可以这样做:

            var a = "I want apple";
            var b = "an";
            var position = 6;
            var output = [a.slice(0, position + 1), b, a.slice(position)].join('');
            console.log(output);

            (编辑:我看到上面确实回答了这个问题,对不起!)

            【讨论】:

              【解决方案9】:

              Underscore.String 库具有执行 Insert 的函数

              插入(字符串、索引、子字符串)=> 字符串

              像这样

              insert("Hello ", 6, "world");
              // => "Hello world"
              

              【讨论】:

              • 不是我,但可能是因为问题中没有提到那个库。但他似乎也不排除其他图书馆 IMO..
              • 即使我不喜欢使用库,除非必要,我还是赞成抵消反对票:P
              【解决方案10】:

              如果您像这样使用 indexOf() 确定 position 可能会更好:

              function insertString(a, b, at)
              {
                  var position = a.indexOf(at); 
              
                  if (position !== -1)
                  {
                      return a.substr(0, position) + b + a.substr(position);    
                  }  
              
                  return "substring not found";
              }
              

              然后像这样调用函数:

              insertString("I want apple", "an ", "apple");
              

              请注意,我在函数调用中的“an”之后放置了一个空格,而不是在 return 语句中。

              【讨论】:

              • 这不是它所要求的。即使是这种情况,如果您多次出现“at”子字符串,这也不起作用
              【解决方案11】:
              var array = a.split(' '); 
              array.splice(position, 0, b);
              var output = array.join(' ');
              

              这会更慢,但会注意在 an 之前和之后添加空间 此外,您必须更改 position 的值(改为 2,现在更直观)

              【讨论】:

                【解决方案12】:

                只是一个小小的改变,因为上面的解决方案输出了

                “我想要一个苹果”

                而不是

                “我想要一个苹果”

                获取输出为

                “我想要一个苹果”

                使用以下修改后的代码

                var output = a.substr(0, position) + " " + b + a.substr(position);
                

                【讨论】:

                • 是的,在 this 的情况下这可能是不可取的,但在 all 的情况下几乎绝对不可取自动添加额外的空格。
                • 正确的解决方案是在字符串中添加空格='an',这样你就可以重用函数
                猜你喜欢
                • 2020-04-22
                • 2019-07-31
                • 1970-01-01
                • 2015-02-11
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2022-01-08
                相关资源
                最近更新 更多