0

I have a set of words I want to match in a given string.

['foo', 'bar']

I only want to match the complete word, so have setup the following test case.

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

How can I match just whole words?

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);
Luke
  • 3,481
  • 6
  • 39
  • 63

0 Answers0