我有以下代码:
var str = "4 shnitzel,5 ducks";
var rgx = new RegExp("[0-9]+","g");
console.log( rgx.exec(str) );
chrome 和 firefox 上的输出是["4"]
.
为什么我没有得到结果["4","5"]
?
exec https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec只搜索下一个匹配项。您需要多次调用它才能获取所有匹配项:
如果您的正则表达式使用“g”标志,则可以多次使用 exec 方法来查找同一字符串中的连续匹配项。
您可以执行此操作来查找所有匹配项exec
:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
match, matches = [];
while ((match = re.exec(str)) !== null) {
matches.push(match[0]);
}
或者您只需使用match method https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match在字符串`str上:
var str = "4 shnitzel,5 ducks",
re = new RegExp("[0-9]+","g"),
matches = str.match(re);
顺便说一句:使用RegExp 文字语法/…/ https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp可能更方便:/[0-9]+/g
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)