Note that there are some explanatory texts on larger screens.

plurals
  1. POMatching a string only if it is not in <script> or <a> tags
    primarykey
    data
    text
    <p>I'm working on a browser plugin that replaces all instances of "someString" (as defined by a complicated regex) with <code>&lt;a href="http://domain.com/$1"&gt;$1&lt;/a&gt;</code>. This generally works ok just doing a global replace on the body's innerHTML. However it breaks the page when it finds (and replaces) the "someString" inside <code>&lt;script&gt;</code> tags (i.e. as a JS variable or other JS reference). It also breaks if "someString" is already part of an anchor.</p> <p>So basically I want to do a global replace on all instances of "someString" unless it falls inside a <code>&lt;script&gt;&lt;/script&gt;</code> or <code>&lt;a&gt;&lt;/a&gt;</code> tag set.</p> <p>Essentially what I have now is:</p> <pre><code>var body = document.getElementsByTagName('body')[0].innerHTML; body = body.replace(/(someString)/gi, '&lt;a href="http://domain.com/$1"&gt;$1&lt;/a&gt;'); document.getElementsByTagName('body')[0].innerHTML = body; </code></pre> <p>But obviously that's not good enough. I've been struggling for a couple hours now and reading all of the answers here (including the many adamant ones that insist regex should not be used with HTML), so I'm open to suggestions on how to do this. I'd prefer using straight JS, but can use jQuery if necessary.</p> <p><strong>Edit - Sample HTML</strong>:</p> <pre><code>&lt;body&gt; someString &lt;script type="text/javascript"&gt; var someString = 'blah'; console.log(someString); &lt;/script&gt; &lt;a href="someString.html"&gt;someString&lt;/a&gt; &lt;/body&gt; </code></pre> <p>In that case, only the very first instance of "someString" should be replaced.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload