我有这样一行:
\/Date(1475832958000)\/
我想从中提取一个数字。我这样做了:
var regex = /(\d+)/;
var str = '\/Date(1475832958000)\/';
console.log(str.match(regex));
//["1475832958000", "1475832958000"]
我得到一个包含 2 个元素的数组。我不懂为什么。请帮忙。
最佳答案
在正则表达式 ()
is using for capturing group 中,第一个元素是完全匹配,第二个元素是捕获的值。
来自MDN docs :
<小时/>An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.
如果您只想获取括号内的数字,请转义括号(通过添加反斜杠,\
)。
var regex = /\(\d+\)/;
var str = '\/Date(1475832958000)\/';
console.log(str.match(regex));
// or in case you just want to get the number
// then use capturing group
var regex1 = /\((\d+)\)/;
console.log(str.match(regex1));
关于javascript - match 函数返回一个包含两个元素而不是一个元素的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43889319/