Check For Multiple Words
I have one problem with this code when I add more than one word to the titleIs Var it does not fire the if statement. The top one does not work ie if a word is in Var titleIs and i
Solution 1:
test
method accepts a single string. (in fact when you send an array with only one element, it takes that element into account).
You need a new method called testAny
to be defined like this:
RegExp.prototype.testAny = function (arr){
for(var i=0; i<arr.length; i++){
if (this.test(arr[i])) returntrue;
}
returnfalse;
}
(in fact matchesAny
is a better name - in my opinion - but used the above name to keep it consistent with the existing test
method)
and then be used in your if
instead.
if(regex.testAny(titleIs)) ...
Solution 2:
RegExp expects a String, not an Array.
So check each word one by one:
var titleIs = ['Knit', 'Main'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
for(var i=0; i<titleIs.length; i++){
if (regex.test(titleIs[i])) {
alert("true")
}
}
The reason it works with just a single item in the Array is that Javascript is coercing your array into the String "Knit"
. With two items in the list it is coerced into "Knit,Main"
and with that comma in the middle no longer matches your regex.
Solution 3:
you should test each string in your array not put your whole array in regex.test
var titleIs = ['Knit', 'Main'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
for(var i=0;i<titleIs.length;i++)
if (regex.test(titleIs[i])) {
alert("true")
break;
}
Post a Comment for "Check For Multiple Words"