Chris
Chris

Reputation: 3657

Getting the last number in a string (JavaScript)

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

Upvotes: 7

Views: 26793

Answers (3)

CodeSlinger
CodeSlinger

Reputation: 429

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

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

Upvotes: 3

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196256

this should do it

var year = str.match(/\d+$/)[0];

Upvotes: 19

Pierre
Pierre

Reputation: 19081

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);

Upvotes: 16

Related Questions