I am trying to parse a big chunk of text to find all the matched keywords.
I have all the keywords in an array.
for eg:
var string = "hi, I need support for apple, android and nokia phones.";
var keywords = ['apple', 'nokia', 'android'];
for(i=0;i<keywords.length; i++){
var match = string.match(keywords[i]);
console.log(match);
}
This is kind of working for now. Just looking for a better and efficient solution.
As @freakish said, combining them into one regexp is more efficient (given a decent regex engine). Of course that requires the matches not to overlap, if you need such you must test them one-by-one.
var match = string.match(new RegExp(keywords.join("|"), "g"));
One way; case-insensitive, whole words, no dups;
var string = "hi, I need support for apple, android and nokia phones.";
var keywords = ['apple', 'nokia', 'android'];
var results = [];
for(var i = 0; i < keywords.length; i++) {
if ((new RegExp("\\b" + keywords[i] + "\\b", "i").test(keywords[i]))) {
results.push(keywords[i]);
}
}
alert( "contains: " + results );