Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight text inside html with jQuery

I am looking to do something similar to this plugin http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

But the problem I am facing is that the above plugin does not allow you to highlight words within html.

So if you are looking for my text

inside html like

this is <a href="#">my</a> text that needs highlighting

You will not get any highlighting.

Is there a way to highlight text while ignoring any html tags in between?

like image 979
Mike Avatar asked Feb 06 '12 21:02

Mike


1 Answers

I fiddled some RegEx which allows HTML tags at the position of whitespace chars:

<div id="test">this is <a href="#">my</a> text that needs highlighting</div>

JavaScript:

var src_str = $("#test").html();
var term = "my text";
term = term.replace(/(\s+)/,"(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("("+term+")", "i");

src_str = src_str.replace(pattern, "<mark>$1</mark>");
src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/,"$1</mark>$2<mark>$4");

$("#test").html(src_str);

Try it here: http://jsfiddle.net/UPs3V/

like image 152
Julien Schmidt Avatar answered Oct 16 '22 00:10

Julien Schmidt