Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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")
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
234 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...