Return true/false for a matched/not matched regex

JavascriptRegex

Javascript Problem Overview


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) - (.*)/);

and I need to return "false" if myS is not in that format, true otherwise.

I mean :

var myS = "00 - ??:??:?? - a";  // TRUE
var myS = "00 - ??:?:?? - a";   // FALSE

how can I check if the regex has matched the string or not?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkzzzView Question on Stackoverflow
Solution 1 - JavascriptLightness Races in OrbitView Answer on Stackoverflow
Solution 2 - Javascriptuser113716View Answer on Stackoverflow
Solution 3 - JavascriptLeslie HanksView Answer on Stackoverflow
Solution 4 - JavascriptMegamind SaikoView Answer on Stackoverflow
Solution 5 - JavascriptSpikePyView Answer on Stackoverflow