【问题标题】:Regex match only exact words [duplicate]正则表达式仅匹配确切的单词[重复]
【发布时间】:2016-12-01 20:18:46
【问题描述】:

我使用以下函数为某些单词提供类名:

$.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);
});
};

问题是它与 this 中的 redundant 匹配。我怎样才能让它只匹配确切的单词(红色但不是多余的)?我做了一些研究,发现我需要做这样的事情:

(\w+)

但我不知道在gi

旁边添加它

我将运行添加的函数 一句话就是:

<p>Only one redundant word is red</p>

$('p').wrapInTag({
      tag: 'span',
      words: ['red']
}, 'blue');

谢谢

【问题讨论】:

  • 从您提供的代码中创建了一个快速的 JSFiddle [jsfiddle.net/611g00n6/],似乎红色正按预期匹配,但“冗余”中的“红色”也是如此。这就是你的问题吗?
  • @Chirag64 是的,这就是问题所在:)

标签: javascript regex


【解决方案1】:

我认为这与(\w+) 无关。如果我正确地阅读了问题,您想匹配一个单词,而不是单词的子字符串。这可以使用字边界\b

来实现

就像\b(is|red|blue)\b 将完全匹配isredblue

MDN on word boundary regex

【讨论】:

  • /(\w+)/gi 不好吗?
  • @mortezaT 我不明白,这如何阻止您匹配单词的子字符串?
猜你喜欢
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-29
相关资源
最近更新 更多