Return true/false for a matched/not matched regex

前端 未结 5 1279
时光说笑
时光说笑 2020-12-25 10:02

I have this regex on Javascript

var myS = \"00 - ??:??:?? - a\";
var removedTL = myS.match(/^(\\d\\d) - (\\?\\?|10|0\\d):(\\?\\?|[0-5]\\d):(\\?\\?|[0-5]\\d)          


        
5条回答
  •  孤城傲影
    2020-12-25 10:53

    Use a double logical NOT operator.

    return !!removedTL;
    

    This will convert to true/false depending on if matches are found.

    No matches gives you null, which is converted to false.

    One or more matches gives you an Array, which is converted to true.


    As an alternative, you can use .test() instead of .match().

    /^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/.test( myS );
    

    ...which gives you a boolean result directly.

提交回复
热议问题