[英]How can I replace everything in HTML body that matches a word?
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>
How can I replace all instances of 123 with Pi using JavaScript or jQuery.如何使用 JavaScript 或 jQuery 将 123 的所有实例替换为 Pi。 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.
我已经简化了示例,以便包含显着功能,如果有什么我可以添加的,请告诉我。
Safest way is to walk the dom, and perform the regex on text nodes only:最安全的方法是遍历 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 );
This starts at a root, and recursively calls the replaceText
function on the child nodes, which are obtained using the contents()
[docs] method.这从根开始,并在子节点上递归调用
replaceText
function,这些子节点是使用contents()
[docs]方法获得的。
If a text node is located, the replace is performed.如果找到文本节点,则执行替换。
Example: http://jsfiddle.net/k6zjT/示例: http://jsfiddle.net/k6zjT/
<script>
$(document).ready(function() {
$("body").html(String($('body').html()).replace(/123/g, 'Pi'));
});
</script>
Here's an entirely pure JavaScript solution to complement Patrick's answer.这是一个完全纯粹的 JavaScript 解决方案,以补充帕特里克的答案。
//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;
}
For fun, here's the code in a sandbox: http://jsfiddle.net/mkmcdonald/th6bh/1/为了好玩,这是沙箱中的代码: http://jsfiddle.net/mkmcdonald/th6bh/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.