views:

111

answers:

3

Hopefully this won't be too difficult, but I'm not too skilled in regular expressions. I have a string that contains two dates and would like to extract the two dates into an array or something using JAVASCRIPT.

Here's my string: "I am available Thursday, October 28, 2009 through Saturday, November 7, 2009"

I would like for the array to be: arr[0] = "Thursday, October 28, 2009" arr[1] = "Saturday, November 7, 2009"

Is this even possible to do?

Thanks for all your help!

+2  A: 

You don't need a regular expression for a (mostly) static string like that. How about:

var s = "I am available Thursday, October 28, 2009 through Saturday, November 7, 2009";
var dates = s.split('available')[1].split('through');
trim(dates[0]); // "Thursday, October 28, 2009"
trim(dates[1]); // "Saturday, November 7, 2009"

trim() strips leading + trailing whitespace:

function trim(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
Crescent Fresh
he could go even simpler than that: dates[0] = "Thursday, October 28, 2009"; dates[1] = Saturday, November 7, 2009"; would do the trick. But presumably he wants to be able to extract dates from an arbitrary string?
Brian Schroth
@Brian: the code shown extracts dates from strings of the form `"... available DATE1 through DATE2"` where `...` is any text.
Crescent Fresh
yeah, the string will change, but will always include that same text, just the dates will change. I think crescentfresh's solution will work! There's some more trailing text after the last date, but I can take care of that! Thank you all for your help!
vcuankit
A: 

With just regular expressions, you could only really make it work for very specifc date formats. So this will match your exact words:

var s="I am available Thursday, October 28, 2009 through Saturday, November 7, 2009";
arr=s.match(/(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[^\d]*\d*, \d*/g);
alert(arr);

But not if someone just typed: "October 28, 2009".

rjmunro
A: 

"(Sunday|Monday|Tuesday|etc), (January|February|etc) [1-3]?[0-9], [0-9][0-9][0-9][0-9]", maybe? Syntax might not be exact for Javascript but that should get the idea across. It would have the potential for false positives (January 39th) but trying to account for complex calendar rules in a regexp is a mistake.

Brian Schroth