Created
February 29, 2016 22:09
-
-
Save kojilab/5dc14501809936a45a8d to your computer and use it in GitHub Desktop.
jQuery Plugin to highlight occurrences of a word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.fn.showKeywords = function(kwds) { | |
kws = kwds || []; | |
if (!$.isArray(kwds) || kwds.length === 0) return this; | |
var str = $.trim(kwds.join('|')); | |
if (str.length === 0) return this; | |
var regex = new RegExp('\\b('+str+')\\b', 'gim'); | |
this.each(function() { | |
var children = $(this).children(); | |
if (children.length > 0) { | |
children.showKeywords(kwds); | |
} else { | |
var html = $(this).html(); | |
html = html.replace(regex, '<em class="occurence">\$1</em>'); | |
$(this).html(html); | |
} | |
}); | |
return this; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment