7

var str = "7-Dec-1985" var str = "12-Jan-1703" var str = "18-Feb-1999"

How would I got about pulling just the year out of the string? I have tried a number of different RegExp but none seem to be working.

I would have expected re = new RegExp(/(\d+)\D*\z/); To have worked but sadly it did not.

Any suggestions would be very appreciated

2
  • Note that re = new RegExp(/(\d+)\D*\z/); is actually creating two regex objects, the first being /(\d+)\D*\z/ which is then passed to the RegExp contstructor. Normally you would use new RegExp only if you have the need construct the pattern dynamically which you would then pass as a string to the constructor. In all other cases re = /(\d+)\D*\z/; is perfectly ok. Commented Dec 6, 2011 at 23:56
  • 1
    There's no reason you need a regular expression here. RegExp is, in general, expensive and should be used with care. Commented Dec 7, 2011 at 0:03

3 Answers 3

19

this should do it

var year = str.match(/\d+$/)[0];
Sign up to request clarification or add additional context in comments.

2 Comments

FYI str.match returns null if nothing found
this does not work if the string has anything else after the last number
16

Since all of your str(s) use - as a separator, this will work for you:

var str = "7-Dec-1985",
    arr = str.split('-'),
    year = arr[2];

console.log(year);

4 Comments

Never use a regex when you can use a split.
Thanks very much, this works perfectly. Turns out though that there is a bit more information after the year. "7-Dec-1985 12:00 AM" Am I able to easily remove the time from the string?
"7-Dec-1985 12:00 AM".split(' ')[0].split('-')[2]
Simply parsing the result into an int solved this issue. Cheers again!
3

I'd try: /.*(\d{4})$/

Test your regex's here: http://www.regular-expressions.info/javascriptexample.html

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.