regex to get the number from the end of a string
我有一个像stringNumber变量的id,如下所示:example12我需要一些javascript正则表达式从字符串中提取12,“example”对于所有id都是不变的,只是数字会不同。
This regular expression matches numbers at the end of the string.
var matches = str.match(/d+$/);
It will return an Array
with its 0
th element the match, if successful. Otherwise, it will return null
.
Before accessing the 0
member, ensure the match was made.
if (matches) {
number = matches[0];
}
jsFiddle.
If you must have it as a Number
, you can use a function to convert it, such as parseInt()
.
number = parseInt(number, 10);
RegEx:
var str = "example12";
parseInt(str.match(/d+$/)[0], 10);
String manipulation:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);
链接地址: http://www.djcxy.com/p/86986.html
上一篇: 正则表达式允许数字值在1之间
下一篇: 正则表达式从字符串的末尾获取数字