Reputation: 6832
String:
Michael Jordan <br> 1963-02-17 Brooklyn, New York
How I can only get 1963-02-17
with regex and JavaScript?
Upvotes: 1
Views: 71
Reputation: 10838
To match this date format specifically (ie YYYY-MM-DD):
var str = 'Michael Jordan <br> 1963-02-17 Brooklyn, New York';
var date = str.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)[0]; //"1963-02-17"
If it won't always have the date in the string, you will want to check for a valid match first:
var str = 'Michael Jordan <br> 19632-17 Brooklyn, New York';
var date = str.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/);
if(date && date[0])
{
date = date[0];
}
//date is "1963-02-17" or NULL
The first example will throw an error if the date is not matched, whereas the second will silently fail and leave date
equal to NULL
Upvotes: 3