Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex not working in JavaScript

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?

like image 525
Trip Avatar asked May 17 '26 05:05

Trip


1 Answers

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:

  1. 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]
    
  2. 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$/

like image 80
Matt Avatar answered May 18 '26 17:05

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!