AJT
AJT

Reputation: 266

JavaScript Regex - Get Nth digits from string

I have a date string being output in this format: 2014-11-28 00:00:00

I'm getting the year with JS match and regex to grab the first four digits: match(/^[0-9]{4}/)

So now I'd like to get the month and the day too. If they are below 10, a 0 is prepended, so I thought the simplest way would be to pull the 6th and 7th characters for the month and the 8th and 9th characters for the day.

How can I do this with regex in jQuery/JavaScript?

Upvotes: 0

Views: 1181

Answers (3)

MH2K9
MH2K9

Reputation: 12039

You can done this using match() or split().

Using match():

var date = '2014-11-28 00:00:00',
    pattern = /^(\d{4})-(\d{1,2})-(\d{1,2})/
    dateElements = date.match(pattern),
    day = dateElements[3],
    month = dateElements[2],
    year = dateElements[1];
alert('Day = ' + day + ', Month = ' + month + ' & Year = ' + year);

Or Using split():

var date = '2014-11-28 00:00:00',
    str = date.substring(0, date.length - 9),
    dateElements = str.split('-'),
    day = dateElements[2],
    month = dateElements[1],
    year = dateElements[0];
alert('Day = ' + day + ', Month = ' + month + ' & Year = ' + year);

Upvotes: 1

rink.attendant.6
rink.attendant.6

Reputation: 46218

Perhaps you can try a different approach to your problem instead of regex?

The Date object seems to be sufficient for your purposes.

var d = new Date('2014-11-28 00:00:00');
d.getFullYear(); // returns 2014
d.getMonth(); // return 10
d.getDay(); // returns 28

If you really want to use regular expressions, this will capture the groups as you wish:

var foo = '2014-11-28 00:00:00'.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
foo[1]; // returns "2014"
foo[2]; // returns "11"
foo[3]; // returns "28"

Read more about regex capturing groups.

Upvotes: 3

John
John

Reputation: 916

This regex will work for your purposes:

/^(\d{4})-(\d{1,2})-(\d{1,2})/

Upvotes: 1

Related Questions