jquery implements the method of highlighting page keywords

  • 2020-05-16 06:17:28
  • OfStack

The example of this article describes the method of jquery to highlight the page keywords. Share with you for your reference. The specific analysis is as follows:

Highlight the page search keywords through jquery
Support Chinese multi-word page highlighting

1. The JavaScript code is as follows:

jQuery.fn.extend({
    highlight: function(search, configs){
        if(typeof(search) == 'undefined') return;
        var configs =  jQuery.extend({
            insensitive: 1, // Match case or not   0 matching 1 Don't match
            hls_class: 'highlight', // Highlighting the class
            clear_last: true, // Clear the previously highlighted result
        },configs);  
        if(configs.clear_last) {
            $(this).find("strong."+configs.hls_class).each(function(){
                $(this).after($(this).text());
                $(this).remove();
            })
        }
        return this.each(function() {
            if(typeof(search) == "string") {
                $(this).highregx(search,configs);
            } else if (search.constructor === Array ) {
                for(var query in search){
                    var search_str = $.trim(search[query]);
                    if(search_str != "") $(this).highregx(search_str,configs);
                }
            }
        });              
    },             
    highregx: function(query,configs){
        query = this.unicode(query);
        var regex = new RegExp("(<[^>]*>)|("+ query +")", configs.insensitive ? "ig" : "g");      
        this.html(this.html().replace(regex, function(a, b, c){
            return (a.charAt(0) == "<") ? a : "<strong class=\""+ configs.hls_class +"\">" + c + "</strong>";
        }));
    },
    unicode: function(s){
         var len=s.length;
         var rs="";
         s = s.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");
         for(var i=0;i<len;i++){
            if(s.charCodeAt(i) > 255)
                rs+="\\u"+ s.charCodeAt(i).toString(16);
            else rs +=  s.charAt(i);
         }  
         return rs;
    } 
});

2. The highlight plug-in can be downloaded here.

I hope this article is helpful for you to design jQuery program.


Related articles: