Reputation: 275
I need to be able to check for required keyword(s).
Here's what i'm currently using:
// Check for all the phrases
for (var i = 0; i < phrases.length; i++) {
if (value.toLowerCase().indexOf(phrases[i].toLowerCase()) < 0) {
// Phrase not found
missingPhrase = phrases[i];
break;
}
}
The problem is that it'll say 'random' is fine if 'randomize' is included.
I found this: how to check if text exists in javascript var (just an example)
But not sure of the best way to incorporate it in jQuery with the possibly to check for multiple keywords.
Upvotes: 1
Views: 419
Reputation: 104494
var value_mod = " " + value + " "; // put a fake white space at the beginning and end so we can have a word boundary at the start and end of the line
var regs = [];
var i;
for (i = 0; i < phrases.length; i++) {
regs.push = new RegExp("\\b" + phrases[i] + "\\b", "i"); /* \b is "word boundary" "i" for case-insensitive */
}
for (i = 0; i < regs.length; i++) {
if (regs[i].test(value_mod)) {
// expression match on whole word.
} else {
missingPhrase = phrases[i];
break;
}
}
}
Upvotes: 1
Reputation: 6773
If you are looking for keywords then why not split() the value on the space character to separate the words into an array. Then loop through the array looking for the keyword.
Taking into account the comments: You should also remove a variety of punctuation characters, maybe replacing them with spaces.
Upvotes: 1
Reputation: 3541
Using the function that you've linked, you can do:
".randomize blah...asd.".containsWord("(hello|blah)")
That's because regexs can match different string as you can see here
In order to make it more readable, you can modify containsWord to accept an array, and escape chars and make the regex based on it.
Good luck!
Upvotes: 1