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. 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:
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.
If a text node is located, the replace is performed.
Example: http://jsfiddle.net/k6zjT/
Here's an entirely pure JavaScript solution to complement Patrick's answer.
//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/
<script>
$(document).ready(function() {
$("body").html(String($('body').html()).replace(/123/g, 'Pi'));
});
</script>
精彩评论