【问题标题】:How can I replace everything in HTML body that matches a word?如何替换 HTML 正文中与单词匹配的所有内容?
【发布时间】:2011-09-30 00:32:07
【问题描述】:

我有一个网页,如下所示:

<html>
  <body>
    <script src="http://www.website.com/123.js" ></script>
    <h1>123 is a great number!</h1>
    Everyone likes 123.
  </body>
<html>

如何使用 JavaScript 或 jQuery 将 123 的所有实例替换为 Pi。我希望在页面加载后立即发生这种情况。完全希望这就像看起来应该的那样简单。我觉得它是沿线

<script>
$(document).ready(function() {
$('body').replace(/123/g, 'Pi');
});
</script>

但我不确定我哪里出错了。我已经简化了示例,以便包含突出的功能,如果有什么我可以添加的,请告诉我。

【问题讨论】:

    标签: javascript jquery regex replace


    【解决方案1】:

    这是一个完全纯 JavaScript 的解决方案来补充 Patrick 的回答。

    //specify a start point
    recurseDOM(document.body);
    
    function recurseDOM(scope)
    {
        var i = 0, nodes, node;
        if(scope.childNodes)
        {
            nodes = scope.childNodes;
            for(i;i<nodes.length;i++)
            {
                node = nodes[i];
                if(node.nodeType === 3)
                {
                    //is a text node
                    checkTextNode(node);    
                }
                if(node.childNodes)
                {
                    //loop through child nodes if child nodes are found
                    recurseDOM(node);
                }
                node = null;
            }
            nodes = null;
        }   
    }
    
    function checkTextNode(node)
    {
        var newText = "is", patt = /is/g, text = node.data, test = patt.test(text);
        if(test)
        {
            //match found, replace node's textual data with specified string
            node.data = text.replace(patt, "__" + newText + "__");
            newText = null;
            text = null;
        }
        test = null;
    }
    

    为了好玩,下面是沙盒中的代码:http://jsfiddle.net/mkmcdonald/th6bh/1/

    【讨论】:

    • Matt:我本来想就没有足够的 jQuery 发表一个聪明的评论,但就是无法让自己去做! ;o) +1
    【解决方案2】:

    最安全的方法是遍历 dom,并且只在文本节点上执行正则表达式:

    var regex = /123/g,
        replacement = 'Pi';
    
    function replaceText(i,el) {
        if (el.nodeType === 3) {
            if (regex.test(el.data)) {
                el.data = el.data.replace(regex, replacement);
            }
        } else {
            $(el).contents().each( replaceText );
        }
    }
    
    $('body').each( replaceText );
    

    从根开始,递归调用子节点上的replaceText函数,通过contents()[docs]方法获取。

    如果找到文本节点,则执行替换。

    示例: http://jsfiddle.net/k6zjT/

    【讨论】:

      【解决方案3】:
      <script>
      $(document).ready(function() {
          $("body").html(String($('body').html()).replace(/123/g, 'Pi'));
      });
      </script>
      

      【讨论】:

      • 这会起作用,尽管当它出现在属性值中时它也会替换“123”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 2016-04-15
      相关资源
      最近更新 更多