简体   繁体   中英

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.

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.

//These results to be highlighted
var results = [];
results[0] = 'jquery';
results[1] = 'json';
results[2] = 'Java Script';
results[3] = 'java';
results[4] = 'java Update';
results[5] = 'javelin';
results[6] = 'James';
results[7] = 'jacob';
results[8] = 'Jail';
results[9] = 'Jailor';

jQuery(document).ready(function(){
    //Search the results
    jQuery('#search').live('keyup', function(event){
        var term = jQuery(this).val();//keyword to be matched
        var htm = '';

        //Keys with codes 40 and below are special (enter, arrow keys, escape, etc.), Key code 8 is backspace.
        if(event.keyCode > 40 || event.keyCode <91  || event.keyCode == 8 ||
          event.keyCode == 20 || event.keyCode == 16 || event.keyCode == 9 ||
          event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 ||
          event.keyCode == 40) {
            for(x in results){
                var match = results[x];
                if(match.toLowerCase().indexOf(term.toLowerCase()) != -1){
                    var o = '<b><u>'+term+'</u></b>';
                    var a = match.replace(term, o);
                    htm += '<li>'+a+'</li>';
                }
            }
            //create a orderd list for the matched results
            var output = '<ol>' + htm + '</ol>';
            if (htm.length > 0) {
                jQuery('#result').show().append(output);
            }
        }
    });
});

The complete tutorial can be found here: http://www.webspeaks.in/2012/09/live-text-search-highlight-using.html

Not sure how well the jQuery plugin works, here is the script I came up with but doesn't highlight text over multiple tags. If I want to highlight "my script" and the html looks like "my script" then it would not be highlighted. Still working on that part.

Here is the script so far:

str='<img src="brown fox.jpg" title="The brown fox" />'
    +'<p>some text containing fox. And onother fox.</p>'
var word="fox";
word="(\\b"+ 
    word.replace(/([{}()[\]\\.?*+^$|=!:~-])/g, "\\$1")
        + "\\b)";
var r = new RegExp(word,"igm")
str.replace(/(>[^<]+)/igm,function(a){
    return a.replace(r,"<span class='hl'>$1</span>");
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM