【问题标题】:Replace substring in string with range in JavaScript用 JavaScript 中的范围替换字符串中的子字符串
【发布时间】:2012-12-05 04:40:33
【问题描述】:

如何在给定起始位置和长度的情况下替换字符串的子字符串?

我希望是这样的:

var string = "This is a test string";
string.replace(10, 4, "replacement");

所以string 等于

"this is a replacement string"

..但我找不到类似的东西。

任何帮助表示赞赏。

【问题讨论】:

    标签: javascript string replace


    【解决方案1】:

    像这样:

    var outstr = instr.substr(0,start)+"replacement"+instr.substr(start+length);
    

    您可以将其添加到字符串的原型中:

    String.prototype.splice = function(start,length,replacement) {
        return this.substr(0,start)+replacement+this.substr(start+length);
    }
    

    (我称之为splice,因为它与同名的Array函数非常相似)

    【讨论】:

      【解决方案2】:

      不管怎样,这个函数将基于两个索引而不是第一个索引和长度来替换。

      splice: function(specimen, start, end, replacement) {
          // string to modify, start index, end index, and what to replace that selection with
      
          var head = specimen.substring(0,start);
          var body = specimen.substring(start, end + 1); // +1 to include last character
          var tail = specimen.substring(end + 1, specimen.length);
      
          var result = head + replacement + tail;
      
          return result;
      }
      

      【讨论】:

        【解决方案3】:

        短正则表达式版本:

        str.replace(new RegExp("^(.{" + start + "}).{" + length + "}"), "$1" + word);
        

        例子:

        String.prototype.sreplace = function(start, length, word) {
            return this.replace(
                new RegExp("^(.{" + start + "}).{" + length + "}"),
                "$1" + word);
        };
        
        "This is a test string".sreplace(10, 4, "replacement");
        // "This is a replacement string"
        

        演示: http://jsfiddle.net/9zP7D/

        【讨论】:

        • 这就是我个人的做法。 ♥ 正则表达式。
        【解决方案4】:

        Underscore String library 有一个拼接方法,它的工作方式与您指定的完全一样。

        _("This is a test string").splice(10, 4, 'replacement');
        => "This is a replacement string"
        

        库中还有很多其他有用的功能。它的时钟大小为 8kb,可在 cdnjs 获取。

        【讨论】:

        • @cr0nicz 我指的是 Underscore.string。检查链接。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        • 2013-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多