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

html, javascript, jquery

Solution

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.

Problem

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.

Original source