Skip to content
Advertisement

How can I replace strings NOT within a link tag?

I am working on this PHP function. The idea is to wrap certain words occuring in a string into certain tags (both, words and tags, given in an array). It works OK!, but when those words occur into a linked text or its ‘src’ attribute, then of course the link is broken and stuffed with tags, or tags that should not be inside a link are generated. This is what I have now:

JavaScript

The function, in this example, should return "string where the word <h2>empresarios</h2> should be replaced; but the word <a href='http://www.empresarios.com'>empresarios</a> should not be replaced inside <a> tags nor in the URL of their 'src' attribute."

I’d like this replacement function to work all throught the string, but not inside tags nor in its attributes!

(I’d like to do what is mentioned in the following thread, it’s just that it’s not in javascript what I need, but in PHP: /questions/1666790/how-to-replace-text-not-within-a-specific-tag-in-javascript)

Advertisement

Answer

Use the DOM and only modify text nodes:

JavaScript

Edited to replace DOMText with DOMText and DOMElement as necessary.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement