0

I have a string like so:

var string = "some text 2012-01-01 some more text here"

I would like to be able to extract the date from this string, or any one like it, and store the 2012-01-01 or whatever date is there to a variable.

I have found the .match() method but I am stuck from there.

Thanks

4 Answers 4

1
var str =  "some text 2012-01-01 some more text here";
var rex = /\d{4}-\d{2}-\d{2}/;
alert(str.match(rex));
Sign up to request clarification or add additional context in comments.

1 Comment

Noting that str.match() will return either an array of one or more matches, or null.
0
var string = "some text 2012-01-01 some more text here";

// you will be using regular expressions
string.match(/(\d{4}-\d{2}-\d{2}/));

3 Comments

The poster is asking how to get the date out of the string, your answer does not answer that.
@epascarello—presumably that's your down vote. Strange, as this answer is almost exactly the same as the accepted answer.
@RobG, person edited within the 3 minutes since that is not the original code which was just date code. :) Original code was just new Date("2012-01-01")
0

Parsing strings is always a pain. Even more so when parsing a date from within a string given the different formats that dates can have. If the date will always be xxxx-xx-xx, then you could use a split() function splitting on a space " ", and then iterate across the array to find a string that could successfully parse to a date.

Based on my experience, however, if you can get it so your date comes to you in a better way, it will be many times easier for you.

2 Comments

The dates will always be in that format. So how would I go about getting the date out of the array?
oh.. others have suggested regex for matching the pattern. if you can guarantee the format, then that's the best. :)
0
var str="some text 2012-01-01 some more text here";
var pattern=/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/gi;
alert(str.match(pattern));

And a jsFiddle if you would like.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.