I would like a JavaScript regular expression that will match time using the 24 hour clock, where the time is given with or without the colon.
For example, I would like to match time in the following formats:
0800
23:45
2345
but that would not match invalid times such as
34:68
5672
On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.
Match(String) Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. Match(String, Int32) Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.
In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.
This should do it:
^([01]\d|2[0-3]):?([0-5]\d)$
The expression reads:
^ Start of string (anchor) ( begin capturing group [01] a "0" or "1" \d any digit | or 2[0-3] "2" followed by a character between 0 and 3 inclusive ) end capturing group :? optional colon ( start capturing [0-5] character between 0 and 5 \d digit ) end group $ end of string anchor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With