var mystring = "growing up my pet dog was named spot";
var words = ['my', 'dog', 'spot'];
var res = words.every(function(word) {
return mystring.indexOf(word) !== -1;
});
If you want to reuse the function in various parts of your application, give it a name, and provide the string to be searched as the second argument, which makes it the this
value.
function hasWordInString(word) {
return this.indexOf(word) !== -1;
}
var res = words.every(hasWordInString, mystring);
The other nice thing about .every()
is that it short-circuits if false
is returned, so the search stops once a non-matching word is found, making it a little more efficient.
Force whole word matching
If you want to ensure that the matched string is a whole word to avoid "dog" matching "dogma" for example, you will need to make use of RegExp word boundaries:
function hasWordInString(word) {
return this.match(new RegExp("\\b"+word+"\\b"))!=null;
}
var res = words.every(hasWordInString,mystring);