2

I have a text string and an array of words. I am trying to see if the words appear in the text and if they do put them in another array.

I have tried:

var aray = ['dies','jam', 'jug', 'march', 'one', 'men', 'all'],
testText = "If one of them dies I will notice that one off my men is missing"
i,found = [];

for(i=0; i < aray.length; i++){
    searchTerm = "/\\b" + aray[i] + "/gi";
    found = testText.match(searchTerm)
}

But found is always "null"

I read that maybe I should construct a new RegExp object, so I tried:

for(i=0; i < aray.length; i++){
    searchTerm = "/\\b" + aray[i] + "/gi";
    found = testText.match(new RegExp(searchTerm, 'gi'));
}

But still found = "null". I have tried changing the regex but if I put the regex directly into the testText.match it works, ie:

searchTerm = "/\\b" + 'dies' + "/gi";
user2343618
  • 165
  • 4
  • 1
    If you want to use a variable in RegEx pattern in JavaScript you must use the `New RegExp()` like this: `var searchTerm = new RegExp("\\b" + aray[i] + "\\b", "gi");` – erosman Jul 09 '14 at 16:12

1 Answers1

0

You can use underscore or lodash or a custom array intersection function:

var array = ['dies','jam', 'jug', 'march', 'one', 'men', 'all'],
testText = "If one of them dies I will notice that one off my men is missing";

var diff = _.intersection(array, testText.split(' '));

console.log(diff);

--> ["dies", "one", "men"]

http://jsfiddle.net/S65Vd/1/

Community
  • 1
  • 1
Dominic
  • 62,658
  • 20
  • 139
  • 163