I use the following function to give certain words spans with classnames:
$.fn.wrapInTag = function(opts, color) {
var tag = opts.tag || 'span'
, words = opts.words || []
, regex = RegExp(words.join('|'), 'gi') // case insensitive
, replacement = '<'+ tag + ' class="' + color +'">$&</'+ tag +'>';
return this.html(function() {
return $(this).html().replace(regex, replacement);
});
};
The problem is it matches redundant in this for example. How can I make it match only the exact words (red but not redundant)? I did some research and found i need to do something like this:
(\w+)
But I dont know where to add it next to gi
The Function i would run to add to a word is:
<p>Only one redundant word is red</p>
$('p').wrapInTag({
tag: 'span',
words: ['red']
}, 'blue');
Thanks
I don't think it has anything to do with (\w+)
. If I'm reading the problem correctly you want to match a word, not substring of a word. This can be achieved using word boundaries \b
Like so \b(is|red|blue)\b
will match exactly is
or red
or blue
.
MDN on word boundary regex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With