Skip to content

Instantly share code, notes, and snippets.

@kojilab
Created February 29, 2016 22:09
Show Gist options
  • Save kojilab/5dc14501809936a45a8d to your computer and use it in GitHub Desktop.
Save kojilab/5dc14501809936a45a8d to your computer and use it in GitHub Desktop.
jQuery Plugin to highlight occurrences of a word
$.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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment