Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a highlight feature for a live search in JavaScript/JQuery

I'm trying to implement a highlighting feature for a livesearch.

What I do is, send an ajax request with an token the user looks for. I receive an html text containing a table.

So I thought I could use a simple regex, looking for the users token and then surround it with a span, but I am receiving some longfilled <a> - Tags, so chances are good that the user types something and I break my HTML by replacing something inside a tag.

So how can I exclude html tags in my search?

Oh I'm using javascript regexp.

like image 284
Johannes Klauß Avatar asked Apr 20 '12 13:04

Johannes Klauß


1 Answers

You would need to load jQuery highlight plugin and then you can just do something like this:

var words = "keyword1,keyword2,keyword3";
var keywords = words.split(',');
for(var i = 0; i < keywords.length; i++) {
    $(selector).highlight($.trim(keywords[i]));
}

If you wanna do highlighting in the entire page, then replace selector with 'body', otherwise use selector for desired element.

like image 174
Ωmega Avatar answered Sep 23 '22 19:09

Ωmega