Char
Char

Reputation: 2133

JavaScript Time Regex for format H:mm

I have regex for time /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/

This validates 24-hr format as well.

What should be the regex if I do not want to accept leading zeroes?

Example:

9:31 not 09:31

Update:

This issue: Regular expression for matching HH:MM time format accepts both with leading and without leading zeroes. But I'm looking for a 24-hr regex that DOES NOT ACCEPT LEADING ZEROES. It's not a duplicate

I tried this:

^([1-9]|1[0-9]|2[0-3]):[0-5][0-9]$

but doesn't accept 0:24

Any ideas? Thank you

Upvotes: 0

Views: 871

Answers (2)

Char
Char

Reputation: 2133

My answer is : ^([0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

I was looking for a regex that does not accept leading zero

Examples:

  • 0:30
  • 9:30 (not 09:30)
  • 0:00 (12 midnight)

https://regex101.com/r/hcjjHN/2

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370769

The second alternation in the capture group matches hours with a leading zero:

0[0-9]

So, just remove that. You can also make the pattern more DRY by using 1? instead of the first two alternations, and \d instead of [0-9], if you want:

^(1?\d|2[0-3]):[0-5]\d$

https://regex101.com/r/jS9TTj/1

Upvotes: 2

Related Questions