正则表达式exec()循环永远不会在JS中终止 [英] Regex exec() loop never terminates in JS
问题描述
var matches;
while(matches = /./g.exec("abc"))
{
console.log("hey");
}
这永远不会终止.我希望它在3个循环后终止.
This never terminates. I expect it to terminate after 3 loops.
警告:请勿在Chrome中运行它,因为无限的日志行会冻结整个系统.在IE中运行它是安全的(它仍然会冻结您的网页,但是您可以转到位置栏,然后按Enter重新加载).
Warning: Don't run it in Chrome because the infinite log lines freeze your entire system. It's safe to run it in IE (it still freezes your webpage but you can go to the location bar and press enter to reload).
推荐答案
这是您应该在循环中执行 exec
的方式:
This is how you should execute exec
in a loop:
var matches;
var re = /./g;
while(matches = re.exec("abc")) {
if (matches.index === re.lastIndex)
re.lastIndex++;
console.log("hey");
}
-
将正则表达式保留在单独的变量中,而不要使用正则表达式文字.
Keep regex in a separate variable rather than using regex literal.
如果正则表达式的
lastIndex
(匹配位置)与所得数组的index
属性相同,则将lastIndex
递增1.Also if
lastIndex
(matched position) of regex is same asindex
property of resulting array then incrementlastIndex
by 1.这篇关于正则表达式exec()循环永远不会在JS中终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!