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 is in var words, fire the if statement.
Thank you for your help!
var titleIs = ['Knit', 'Main'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
if (regex.test(titleIs)) {
alert("true")
}
These two work:
var titleIs = ['Woven'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
if (regex.test(titleIs)) {
alert("true")
}
var titleIs = ['Main'];
var words = ['Woven', 'Main'];
var regex = new RegExp('^(' + words.join('|') + ')$');
if (regex.test(titleIs)) {
alert("true")
}
you should test each string in your array not put your whole array in regex.test
RegExp expects a String, not an Array.
So check each word one by one:
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.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:(in fact
matchesAny
is a better name - in my opinion - but used the above name to keep it consistent with the existingtest
method)and then be used in your
if
instead.