How can I replace everything in an HTML tag that matches a word?

I have a webpage as 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 to replace all 123 instances with Pi using JavaScript or jQuery. I would like this to happen right after the page loads. I fully hope that it is as simple as it seems. I feel him along the lines

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

But I'm not sure where I am going wrong. I simplified the example to include basic functions, please let me know if there is anything that I can add.

+2
source share
3 answers

The safest way is to walk around dom and perform regular expression only on text nodes:

 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 the root and calls the replaceText function replaceText on the child nodes that are obtained using contents() [docs] .

If the text node is found, a replacement is performed.

Example: http://jsfiddle.net/k6zjT/

+2
source
 <script> $(document).ready(function() { $("body").html(String($('body').html()).replace(/123/g, 'Pi')); }); </script> 
+1
source

Here's a completely clean 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 textual data with specified string node.data = text.replace(patt, "__" + newText + "__"); newText = null; text = null; } test = null; } 

For fun, here is the code in the sandbox: http://jsfiddle.net/mkmcdonald/th6bh/1/

+1
source

All Articles