【发布时间】:2018-06-18 06:20:53
【问题描述】:
我有一个类似 stringNumber 的 id 变量,如下所示:example12 我需要一些 javascript 正则表达式来从字符串中提取 12。“example”对于所有 id 都是恒定的,只是数字会有所不同。
【问题讨论】:
标签: javascript regex
我有一个类似 stringNumber 的 id 变量,如下所示:example12 我需要一些 javascript 正则表达式来从字符串中提取 12。“example”对于所有 id 都是恒定的,只是数字会有所不同。
【问题讨论】:
标签: javascript regex
这个正则表达式匹配字符串末尾的数字。
var matches = str.match(/\d+$/);
如果成功,它将返回一个 Array 及其 0th 元素匹配。否则,它将返回null。
在访问0 成员之前,请确保匹配成功。
if (matches) {
number = matches[0];
}
如果一定要Number,可以用函数来转换,比如parseInt()。
number = parseInt(number, 10);
【讨论】:
[0-9] 比使用\d 更有效。见stackoverflow.com/questions/16621738
\d(除非它成为性能瓶颈)
正则表达式:
var str = "example12";
parseInt(str.match(/\d+$/)[0], 10);
字符串操作:
var str = "example12",
prefix = "example";
parseInt(str.substring(prefix.length), 10);
【讨论】: