我使用以下函数为某些单词提供类名:
$.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);
});
};
Run Code Online (Sandbox Code Playgroud)
问题是它例如在此匹配冗余。我怎样才能让它只匹配确切的单词(红色但不多余)?我做了一些研究,发现我需要做这样的事情:
(\w+)
Run Code Online (Sandbox Code Playgroud)
但我不知道在gi旁边添加它的位置
我要运行以添加到单词的函数是:
<p>Only one redundant word is red</p>
$('p').wrapInTag({
tag: 'span',
words: ['red']
}, 'blue');
Run Code Online (Sandbox Code Playgroud)
谢谢
我不认为这与(\w+). 如果我正确阅读问题,您想匹配一个单词,而不是单词的子字符串。这可以使用字边界来实现\b
像这样\b(is|red|blue)\b将完全匹配is或red或blue。