Skip to content

Instantly share code, notes, and snippets.

@stewartknapman
Last active December 23, 2015 11:49
Show Gist options
  • Save stewartknapman/6630609 to your computer and use it in GitHub Desktop.
Save stewartknapman/6630609 to your computer and use it in GitHub Desktop.
jQuery plugin that searches for a given word or phrase inside a container element and wraps it in some markup.
(function($){
$.fn.textNodes = function(){
return this.find(":not(iframe)").addBack().contents().filter(function(){
return this.nodeType === 3;
});
};
/* wordSearch jQuery plugin */
$.fn.wordSearch = function(searchTerm, options){
var _settings = $.extend( {}, $.fn.wordSearch.defaultSettings, options );
return this.each(function(){
return $(this).textNodes().filter(function(){
return _settings.wordMatcher(searchTerm).test(this.nodeValue);
}).replaceWith(function(){
return (this.nodeValue || "").replace(_settings.wordMatcher(searchTerm), function(original, a, highlightable){
var highlighted;
highlighted = _settings.wordWrapper(searchTerm, highlightable);
if (original === highlightable) {
return highlighted;
} else {
return original.replace(highlightable, highlighted);
}
});
});
});
};
/* settings for overriding plugin functionality */
$.fn.wordSearch.defaultSettings = {
wordMatcher: function(word){
word = RegExp.escape(word);
return new RegExp("(\\b|[_]{1})(" + word + "([e']?s|[^aiou ]s)|" + word + ")([_]{1}|\\b)", "gi");
},
wordWrapper: function(searchTerm, foundContent){
return '<span data-search-term="'+searchTerm+'">'+foundContent+'</span>';
}
};
}(jQuery));
/*
usage:
$('.myContainer').wordSearch('text');
<div class="myContainer">
This is some dummy text.
<strong>this is some nested and uppercase dummy TEXT.</strong>
</div>
output =>
<div class="myContainer">
This is some dummy <span data-search-term="text">text</span>.
<strong>this is some nested and uppercase dummy <span data-search-term="text">TEXT</span>.</strong>
</div>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment