JQuery for finding / replacing html text if not inside an html tag other than P, DIV, SPAN, TD

I have an html text snippet that is part of the DOM of the page in which I need to run find / replace, and I need help determining the best way to create the find / replace function.

For example, I would like to take the contents of the dom object, id = "content" and run find using the target search phrase.

I need a function to replace each instance of a phrase that it finds in the content with "<b> The Phrase </b>", provided that the phrase does not appear inside any tag other than div, p, span or td and return the replaced xhtml text.

Can I do this with jQuery dom traversal along with some substitution method?

+1
source share
2 answers

This is what I used to search the search string. RegEx checks text that does not belong to the HTML tag. In the replace $& function, $& refers to the string that was matched.

 var rx = new RegExp('(?![^<]+>)' + searchString, 'gi'); $(this).html(function (i, html) { return html.replace(rx, '<b>$&</b>') }); 

For non-other HTML tags, you need to give an example. Where it can get complicated.

+2
source

If you want to avoid &nbsp; , you can use this regular expression (?![^<&]+[>;]) Using John Strickler's comment:

 var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi'); $(this).html(function (i, html) { return html.replace(rx, '<b>$&</b>') }); 
0
source

All Articles