获取字符串中的最后一个数字 (JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8408563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:21:35  来源:igfitidea点击:

Getting the last number in a string (JavaScript)

javascriptregex

提问by Chris Turner

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

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.

我如何才能从字符串中提取年份?我尝试了许多不同的 RegExp,但似乎都没有工作。

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

我原以为re = new RegExp(/(\d+)\D*\z/);To 会起作用,但遗憾的是它没有。

Any suggestions would be very appreciated

任何建议将不胜感激

回答by Pierre

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

由于您的所有str(s)都-用作分隔符,因此这对您有用:

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

console.log(year);

回答by Gabriele Petrioli

this should do it

这应该这样做

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

回答by CodeSlinger

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

我会尝试: /.*(\d{4})$/

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

在此处测试您的正则表达式:http: //www.regular-expressions.info/javascriptexample.html