Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match only exact words [duplicate]

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

like image 672
vinni Avatar asked Oct 16 '25 04:10

vinni


1 Answers

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

like image 118
r0dney Avatar answered Oct 17 '25 18:10

r0dney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!