Saint Dave
Saint Dave

Reputation: 567

.match returns null on trying to match a regular expression that is correct and has a match

I have been stuck trying to figure out why my JavaScript code that is supposed to return a match for a regular expression returns null.

I am basically trying to get the date from a google calendar feed using regex and I have tested the regex and its working fine in regexpal.com.

Here is my code:

var eventTextDate = String(value.summary);
var patt1 = /([A-Z][a-z]{2} ){2}\d+, \d+ \d+:\d+.m/;
var eventDate = eventTextDate.match(patt1);

value.summary equals the following:

When: Tue Jan 21, 2014 1:30pm to 3pm 
GMT<br />

Note the newline and forward slashes. I thought they might have something to do with it so I tried to substring(5,30) the string to get rid of the slashes and newlines but that didn't seem to help.

Also, if I change the regex to something like /.../ it does return the three first letter. So I know the basic mechanism and structure of my code works.

I guess my regular expression has some error (even though it works on regexpal.com) as I am new to regex.

I would really appreciate any help or tips for me regarding this issue.

Upvotes: 0

Views: 1478

Answers (1)

KeyNone
KeyNone

Reputation: 9150

You may use

When:\s(.*)\s

as your regular expression.
The date-string will then be in the frist capturing group, accessible as the second index of the match-array, for example:

var re = /When:\s(.*)\s/; 
var str = 'When: Tue Jan 21, 2014 1:30pm to 3pm\nGMT<br />';
var m = str.match(re);

alert(m[1]);

If you don't need the to 3pm part, then modify the regex to

When:\s(.*)\sto

Upvotes: 1

Related Questions