Trip
Trip

Reputation: 27114

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?

Upvotes: 2

Views: 2980

Answers (7)

Kash
Kash

Reputation: 9019

Your regex seems to be right. Incorporating some ideas above, you could test your string like this with Regex:

^(1[0-2]|\d):[0-5]\d [aApP][mM]$

And the testing code in Javascript:

var regex = /^(1[0-2]|\d):[0-5]\d [aApP][mM]$/g; 
    var input = "2:30 PM"; 
    if(regex.test(input)) {
      var matches = input.match(regex);
      for(var match in matches) {
        alert(matches[match]);
      } 
    } else {
      alert("No matches found!");
    }

Upvotes: 1

Marlon León
Marlon León

Reputation: 170

I've tried your code in http://www.regular-expressions.info/javascriptexample.html and it worked.

By the way, you also need to test if the time is valid. Your code now can accept things like this 99:12 AM as if they were correct. I suggest you to use something like this.

\b(1[0-2]|\d):[0-5][0-9]\s([aApP][mM])\b

=)

Upvotes: 1

d_inevitable
d_inevitable

Reputation: 4451

Combining the ideas of Matt, c0deNinja and my own you should end up with:

/^(0?[1-9]|1[0-2]):[0-5][0-9]\s?[AP]M$/.test(input);

Upvotes: 1

Matt
Matt

Reputation: 75307

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$/

Upvotes: 6

c0deNinja
c0deNinja

Reputation: 3986

How about something like this:

.match(/([0]?[1-9]|1[0-2])(:)[0-5][0-9]?( )?(AM|PM)/)

Upvotes: 2

Charles
Charles

Reputation: 11757

If your problem is new line character. You can try:

'12:30 
AM'.replace(/\n/, '').match(/\d{1,2}:\d\d\s((AM)|(PM))/)

Upvotes: 1

d_inevitable
d_inevitable

Reputation: 4451

Assuming that you are checking it on single line input field (and not searching it inside a text area), you should do:

/^\d{1,2}:\d\d\s[AP]M$/

Upvotes: 4

Related Questions