我有一个类似 stringNumber 的 id 变量,如下所示:example12 我需要一些 javascript 正则表达式来从字符串中提取 12。“example”对于所有 id 都是不变的,只是数字会有所不同。
最佳答案
此正则表达式匹配字符串末尾的数字。
var matches = str.match(/\d+$/);
如果成功,它将返回一个 Array
,其 0
元素匹配。否则,它将返回 null
。
在访问 0
成员之前,确保匹配成功。
if (matches) {
number = matches[0];
}
jsFiddle .
如果你必须把它作为一个Number
,你可以使用一个函数来转换它,比如parseInt()
。
number = parseInt(number, 10);
关于javascript - 正则表达式从字符串末尾获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6340180/