0

I need to replace some words with a html link tag, but I ONLY want to do this when the word is NOT found inside an existing link element.

So I'd like to replace FOO in this markup:

<p>Once upon a FOO there was a BAR</p>

But I do NOT want to replace FOO in this markup:

<p>Once upon a <a href="coolsite.net">FOO</a> there was a BAR</p>

I don't really understand how to solve this. I'm guessing something to do with look aheads and look behinds, but I don't really know where to start.

It's ok to run it server side to avoid Safaris limited support for look ahead/behinds.

Johan Nordberg
  • 3,621
  • 4
  • 33
  • 58
  • 2
    Regular expressions are not powerful enough to understand HTML's syntax, which you'll need in the more interesting cases, like `FOO` (this is inside an existing link element) and `FOO` (this is not). You may have to use an HTML parser. https://stackoverflow.com/questions/1732348 – Wander Nauta Sep 18 '20 at 08:01
  • 3
    Alternatively, if you are already in the browser, you may want to do this by walking the DOM, either directly or using a library like jQuery. – Wander Nauta Sep 18 '20 at 08:31

0 Answers0