I am trying to make sure that the format people input is exactly this :
.match(/\d{1,2}:\d\d\s((AM)|(PM))/)
Meaning that a user could write :
12:30 AM
2:30 PM
But not :
1:2 A
1:30
PM
It needs to be first two digits, followed by a colon, than two more digits, a space, and either AM or PM. But my regex expression isn't that. What am I missing?
What exactly seems to be the problem?
> "1:2 A".match(/\d{1,2}:\d\d\s((AM)|(PM))/);
null
>"12:30 AM".match(/\d{1,2}:\d\d\s((AM)|(PM))/);
["12:30 AM", "AM", "AM", undefined]
However:
You need to ground your expression to the start (^) and end ($) of the string otherwise;
> "foo 12:30 AM foo".match(/\d{1,2}:\d\d\s((AM)|(PM))/);
["12:30 AM", "AM", "AM", undefined]
Look at RegExp.test() instead, which returns a simpler true/false rather than an array.
> /^\d{1,2}:\d\d\s((AM)|(PM))$/.test("12:30 AM");
true
A simpler expression which does the same thing could be /^\d{1,2}:\d{2} [AP]M$/
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