Search code examples
javascripttestingwords

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

Solution

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