Return true/false for a matched/not matched regex

前端 未结 5 1170
时光说笑
时光说笑 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:41

    The more appropriate function here might be RegExp.test, which explicitly gives you true or false.

    console.log(/lolcakes/.test("some string"));
    // Output: false
    
    console.log(/lolcakes/.test("some lolcakes"));
    // Output: true
    
    0 讨论(0)
  • 2020-12-25 10:50
    var myS = "00 - ??:??:?? - a";
    var patt = new RegExp("^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)");
    var removedTL = patt.test(myS);
    

    removedTL will hold a boolean value true if matched, false if not matched

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-25 10:54

    The match method will return null if there is no match.

    0 讨论(0)
  • 2020-12-25 10:59

    Since I also prefer using match you could do the following workaround to get a Boolean result:

    var myS = "00 - ??:??:?? - a"
    var removedTL = myS.match(/^(\d\d) - (\?\?|10|0\d):(\?\?|[0-5]\d):(\?\?|[0-5]\d) - (.*)/) != null
    
    0 讨论(0)
提交回复
热议问题