为什么这个单词边界正则表达式不符合预期?

时间:2019-04-18 11:21:49

标签: javascript regex

我要在给定的字符串中匹配一组单词。

['foo', 'bar']

我只想匹配完整的单词,所以请设置以下测试用例。

var data = "I love foo, it's barb."
var words = ['foo', 'bar'];

我该如何匹配整个单词?

var data = 'I love foo its barb.';
var words = ['foo', 'bar'];
var matches = data.match(new RegExp('(\b' + words.join('\b|\b') + '\b)', 'ig'));
console.log(matches);

var data = 'I love foo its barb.';
var words = ['foo', 'bar'];
var matches = data.match(new RegExp('(' + words.join('|') + ')', 'ig'));
console.log(matches);

0 个答案:

没有答案