4

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

Chirag Bhatia - chirag64
  • 4,430
  • 3
  • 26
  • 35
vinni
  • 633
  • 2
  • 8
  • 32

1 Answers1

11

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

r0dney
  • 735
  • 2
  • 5
  • 16