Javascript regex从字符串末尾获取数字

Javascript regex从字符串末尾获取数字,javascript,regex,Javascript,Regex,我有一个类似stringNumber的id变量,如下所示:example12 我需要一些javascript正则表达式来从字符串中提取12。对于所有id,“example”都是常量,只是数字不同。此正则表达式匹配字符串末尾的数字 var matches = str.match(/\d+$/); 如果成功,它将返回一个数组,其中包含匹配的0th元素。否则,它将返回null 在访问0成员之前,请确保已进行匹配 if (matches) { number = matches[0]; }

我有一个类似stringNumber的id变量,如下所示:example12
我需要一些javascript正则表达式来从字符串中提取12。对于所有id,“example”都是常量,只是数字不同。

此正则表达式匹配字符串末尾的数字

var matches = str.match(/\d+$/);
如果成功,它将返回一个
数组
,其中包含匹配的
0
th元素。否则,它将返回
null

在访问
0
成员之前,请确保已进行匹配

if (matches) {
    number = matches[0];
}

如果必须将其作为
编号
,则可以使用函数对其进行转换,例如
parseInt()

正则表达式:

字符串操作:

var str = "example12",
    prefix = "example";
parseInt(str.substring(prefix.length), 10);

提示:使用
[0-9]
比使用
\d
更有效。See@Marathon55很可能是这样,但我仍然会自己使用
\d
(除非它成为性能瓶颈)
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
var str = "example12",
    prefix = "example";
parseInt(str.substring(prefix.length), 10);