I am working on a browser plugin that replaces all instances of "someString" (as defined by a complex regular expression) with <a href="http://domain.com/$1">$1</a> . This usually works fine, making a global replacement on the innerHTML body. However, it breaks the page when it finds (and replaces) "someString" inside the <script> tags (i.e. Like a JS variable or other JS link). It also breaks if "someString" is already part of the binding.
So basically I want to make a global replacement in all instances of "someString" if it doesn't fall into the <script></script> or <a></a> .
Essentially, I have:
var body = document.getElementsByTagName('body')[0].innerHTML; body = body.replace(/(someString)/gi, '<a href="http://domain.com/$1">$1</a>'); document.getElementsByTagName('body')[0].innerHTML = body;
But obviously this is not very good. I struggled for hours and read all the answers here (including the many stubborn ones who insist on regex should not be used with HTML), so I'm open to suggestions on how to do this. I would prefer to use direct JS, but can use jQuery if necessary.
Edit - HTML Example :
<body> someString <script type="text/javascript"> var someString = 'blah'; console.log(someString); </script> <a href="someString.html">someString</a> </body>
In this case, only the very first instance of "someString" should be replaced.
source share