【问题标题】:JQuery: how to replace all between certain characters?JQuery:如何在某些字符之间全部替换?
【发布时间】:2012-06-17 00:09:20
【问题描述】:

我已经寻找了一个通用的解决方案,但只能找到人们特定问题的答案。

基本上,我想知道如何使用 .replace() 替换字符串中任何类型字符之间的项目,例如:

替换 abc 和 xyz 之间的所有文本,包括:abc text to be replaced xyz

或替换 <img and /> 之间的所有文本,例如:<img src="image.jpg" />

任何人都可以帮助我或为我指出一个好的方向吗?

谢谢!如果我需要进一步澄清,请告诉我。

【问题讨论】:

    标签: jquery replace


    【解决方案1】:

    您要查找的内容称为正则表达式。有关更多信息,您可以访问以下网站: http://www.regular-expressions.info/

    请注意,正则表达式并非特定于 JavaScript。

    对于您的具体示例:

    string.replace(/abc.+xyz/,"abc"+newString+"xyz");
    

    。表示任何字符,+ 表示出现一次或多次。

    如果您有多个替代品要做,请尝试:

    string.replace(/abc.+?xyz/g,"abc"+newString+"xyz");
    

    g 代表一般,而 ?是惰性量词,意味着它将在字符串中下一次出现 xyz 时停止。

    【讨论】:

    • 你可能想使用惰性量词。
    • 感谢 Christophe,但我似乎无法在不止一次的情况下使用它。我尝试过的字符串有几个图像实例 并使用 .replace(//,"");我能够删除第一个,但不能删除其他任何一个。这应该调整吗?
    • 对于多次出现,我已经更新了答案,并根据@ddlshack 的建议包含了惰性量词。
    【解决方案2】:

        String.prototype.replaceBetween = function(opentag, closetag, replacement) {
          var read_index = 0;
          var open_index = 0;
          var close_index = 0;
          var output = '';
    
          while ((open_index = this.indexOf(opentag, read_index)) != -1) {
            output += this.slice(read_index, open_index) + opentag;
            read_index = open_index + opentag.length;
    
            if ((close_index = this.indexOf(closetag, read_index)) != -1) {
              if (typeof replacement === 'function') {
                output += replacement(this.substring(open_index + opentag.length, close_index - 1)) + closetag;
              } else {
                output += replacement + closetag;
              }
              read_index = close_index + closetag.length;
            }
          }
    
          output += this.slice(read_index);
    
          return output
        };
    
        var mydiv = document.getElementById("mydiv");
        var html = mydiv.innerHTML;
        html = html.replaceBetween("<b>", "</b>", "hello");
        html = html.replaceBetween("<b>", "</b>", function(body) {
          return body + ' world';
        });
        mydiv.innerHTML = html;
    &lt;div id="mydiv"&gt;The begining...&lt;b&gt;for&lt;/b&gt; and &lt;b&gt;bar&lt;/b&gt;... the end.&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      相关资源
      最近更新 更多