I want to replace some words of the document without changing any html tags or js codes.
Basically what I do is;
document.body.innerHTML = document.body.innerHTML.replace('lorem','new lorem');
But this code will replace any 'lorem'. I want to avoid tags like; <script... var lorem = 123; <div class="lorem", <a id="lorem"
etc.
How can I do this in JS?
Walk the DOM, and
.replace()
the values of text nodes.Another way of doing this is using regular expressions, science you can't insert HTML tags to a text node.
First I am using a regular expressions to catch parts of the body.innerHTML property that are outside of the HTML tags.
But, the string contains also another data, and if I will directly replace it with thge new data some text will be lost.
Insted, I get each match as an argument for a function, and inside this function I use another regular expression.
Notice that you have to replace "foo" twice.
The code:
document.body.innerHTML=document.body.innerHTML.replace(/<[^(script)][^>]*>[^<]*(foo)[^<]*</g,function(match){ return match.replace(/foo/,"newWord"); });