Regex exec() loop never terminates in JS

天涯浪子 提交于 2021-01-20 07:26:40

问题


var matches;

while(matches = /./g.exec("abc"))
{
    console.log("hey");
}

This never terminates. I expect it to terminate after 3 loops.

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).


回答1:


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.

  • Also if lastIndex (matched position) of regex is same as index property of resulting array then increment lastIndex by 1.




回答2:


It's because you are creating a new object with the g flag every time, instead of keeping one regex object. The regex object keeps track of the last match. Since you are creating new objects every time, the object starts from the beginning.

Each regex literal is it's own object that's why:

/./g !== /./g


来源:https://stackoverflow.com/questions/33015942/regex-exec-loop-never-terminates-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!