-->

Check for multiple words

2019-08-25 14:32发布

问题:

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")
}

回答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])) return true;
    }
    return false;
}

(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)) ...


回答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.



回答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;
}