Created
June 26, 2013 20:07
-
-
Save yitsushi/5871142 to your computer and use it in GitHub Desktop.
JavaScript: (un)Highlighting Text #snippet
This file contains hidden or 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
var TextUtil = (function() { | |
return { | |
highlight: function (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; | |
}, | |
unhighlight: function (text, tag) { | |
// Default tag if no tag is provided | |
tag = tag || 'span'; | |
var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g'); | |
return text.replace(re, ''); | |
} | |
}; | |
}()); | |
element.innerHTML = TextUtil.highlight( | |
element.innerHTML, // the text | |
['highlight', 'me', 'is', 'cool'], // 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