Skip to content

Instantly share code, notes, and snippets.

@gentoid
Created February 10, 2013 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gentoid/4750765 to your computer and use it in GitHub Desktop.
Save gentoid/4750765 to your computer and use it in GitHub Desktop.
Highlight text
function highlight(text, words, tag) {
// Default tag if no tag is provided
tag = tag || 'span';
var i, len = words.length, re;
for (i = 0; i < len; i++) {
// Global regex to highlight all matches
re = new RegExp(words[i], 'g');
if (re.test(text)) {
text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
}
}
return text;
}
function unhighlight(text, tag) {
// Default tag if no tag is provided
tag = tag || 'span';
var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g');
return text.replace(re, '');
}
$('p').html( highlight(
$('p').html(), // the text
['foo', 'bar', 'baz', 'hello world'], // list of words or phrases to highlight
'strong' // custom tag
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment