javascript - match string against the array of regular expressions

前端 未结 8 1559
予麋鹿
予麋鹿 2020-12-02 22:23

Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?

The example would be (where the \'if\' statemen

8条回答
  •  被撕碎了的回忆
    2020-12-02 22:39

    Using a more functional approach, you can implement the match with a one-liner using an array function:

    ECMAScript 6:

    const regexList = [/apple/, /pear/];
    const text = "banana pear";
    const isMatch = regexList.some(rx => rx.test(text));
    

    ECMAScript 5:

    var regexList = [/apple/, /pear/];
    var text = "banana pear";
    var isMatch = regexList.some(function(rx) { return rx.test(text); });
    

提交回复
热议问题