如何替换匹配单词的HTML正文中的所有内容?

问题描述:

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

I have a webpage, like the one below:

<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。我希望一旦页面加载后立即发生这种情况。完全希望这看起来应该是这么简单。我觉得这是按照

How can I replace all instances of 123 with Pi using JavaScript or jQuery. I'd like this to occur immediately once the page is loaded. Totally hope this is as easy as it seems like it should be. I sense that it's along the lines of

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

但我不确定我哪里出错了。我已经简化了示例,以便包含显着的功能,如果有任何我可以添加的内容,请告诉我。

But I'm not sure where I'm going wrong. I've simplified the example so that the salient features are included, please let me know if there's anything I can add.

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

Safest way is to walk the dom, and perform the regex on text nodes only:

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 $ c子节点上的$ c>函数,使用 contents()$获得c $ c> [docs] 方法。

This starts at a root, and recursively calls the replaceText function on the child nodes, which are obtained using the contents()[docs] method.

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

If a text node is located, the replace is performed.

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