【发布时间】: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