I have javascript code that works pretty well like:
var rgx = /MyName/g;
var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace(rgx, "<span><span class='myName'>MyNameReplace</span></span>");
The problem is that its matching the regex even in scenarios where it is contained within HTML attributes and what-not. How can I modify the regex so that it will only find it within the content of the HTML? For example, in this string
<div class="someclass" title="MyName">
MyName
</div>
it currently results like (note the change in the title attribute):
<div class="someclass" title="<span><span class='myName'>MyNameReplace</span</span>">
<span><span class='myName'>
MyNameReplace</span></span>
</div>
But I need it to be (leave the title attribute untouched):
<div class="someclass" title="MyName">
<span><span class='myName'>MyNameReplace</span></span>
</div>
Your best bet, and it’s a lot easier than it sounds, is not to try to use regex to parse HTML, but to take advantage of the fact that the DOM already has and recursively process the text nodes.
Here’s an off-the-cuff:
Which you’d call like this:
Live Example: