正则表达式从字符串的末尾获取数字 [英] regex to get the number from the end of a string
问题描述
我有一个类似stringNumber变量的id,如下所示:example12
我需要一些javascript正则表达式从字符串中提取12个。example对于所有id都是常量,只是数字会不同。
i have a id like stringNumber variable like the one as follows : example12 I need some javascript regex to extract 12 from the string."example" will be constant for all id and just the number will be different.
推荐答案
这个正则表达式匹配字符串末尾的数字。
This regular expression matches numbers at the end of the string.
var matches = str.match(/\d+$/);
它将返回数组
及其 0
匹配的元素,如果成功。否则,它将返回 null
。
It will return an Array
with its 0
th element the match, if successful. Otherwise, it will return null
.
在访问 0 $ c $之前c>成员,确保匹配。
Before accessing the 0
member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle 。
如果你必须将它作为数字
,你可以使用函数来转换它,例如 parseInt()
。
If you must have it as a Number
, you can use a function to convert it, such as parseInt()
.
number = parseInt(number, 10);
这篇关于正则表达式从字符串的末尾获取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!