I'm trying to extract the year from a timestamp using regex, but I'm not very good at it, so my code isn't returning what expected.
that's the string: 'Sun Jan 01 2012 00:00:00 GMT+0000 (GMT)'
I need to extract '2012' here's my code:
var scrollDate = tl.getBand(0).getCenterVisibleDate(); // my timestamp
// regex function
function extractNumbers(str) {
var m = /(^|\s)(\d{4})(\s|$)/.exec(str);
return m;
}
// click event
$('.n-left').click(function(){
alert(extractNumbers(scrollDate));
});
The alert box returns this: 2012 , ,2012,
What am I doing wrong? Thanks in advance
I'm trying to extract the year from a timestamp using regex, but I'm not very good at it, so my code isn't returning what expected.
that's the string: 'Sun Jan 01 2012 00:00:00 GMT+0000 (GMT)'
I need to extract '2012' here's my code:
var scrollDate = tl.getBand(0).getCenterVisibleDate(); // my timestamp
// regex function
function extractNumbers(str) {
var m = /(^|\s)(\d{4})(\s|$)/.exec(str);
return m;
}
// click event
$('.n-left').click(function(){
alert(extractNumbers(scrollDate));
});
The alert box returns this: 2012 , ,2012,
What am I doing wrong? Thanks in advance
Share Improve this question asked Sep 7, 2012 at 16:03 Mauro74Mauro74 4,82615 gold badges61 silver badges83 bronze badges 1- 1 Don't use a regex for this, it's the wrong tool for the job, use James Kleeh's approach of just letting Date parse the string. – CaffGeek Commented Sep 7, 2012 at 16:16
3 Answers
Reset to default 7var x = new Date("Sun Jan 01 2012 00:00:00 GMT+0000 (GMT)");
alert(x.getUTCFullYear());
That regular expression uses capture groups. If you look at the return value of exec()
, you’ll notice it looks something like this:
[" 2012 ", " ", "2012", " "]
So, you might want to write extractNumbers()
something like this:
function extractNumbers(str) {
var m = /(^|\s)(\d{4})(\s|$)/.exec(str);
if (m) {
return m[2];
}
}
FWIW, you can use non-capturing groups to group parts of the regexp but only capture what you need. A regexp like this:
/(?:^|\s)(\d{4})(?:\s|$)/
Would return a match array like this:
[" 2012 ", "2012"]
EDIT: …but James Kleeh’s answer is like a much nicer option.
First, it works with RegexBuddy (it returns group #1 successfully).
Another regex you might wanna try, which looks simpler to me: .+?\d\d (\d+)
(then take group #1)