RegExp.exec无限循环

时间:2017-12-13 09:32:18

标签: javascript regex

为什么我在这个

中有无限循环
var sRegexp=new RegExp("([\\d\\s\\.]+)\\s*("+iconsStr+")","g"),value;
var nodeValue=this.nodeValue;

while(value=sRegexp.exec(nodeValue)) {
     alert(sRegexp.lastIndex);
}

lastIndex也是infilite而且值返回相同的结果(因为没有' g'标志),无法理解原因。

更新:我解决了,问题是我在while()中使用了noveValue.reaplce(),抱歉我没有发布所有代码......

1 个答案:

答案 0 :(得分:0)

因为while循环的条件每次都匹配,因为你必须截断或改变任何变量。

Like:


var sRegexp=new RegExp("([\\d\\s\\.]+)\\s*("+iconsStr+")","g");
var value=sRegexp.exec(nodeValue);
console.log(value);
    for(item in value)
    {
       if(!isNaN(parseInt(item)))
       {
         console.log(item + ", " + value[item]); //in this item return the index of every array element and value[item] provide the matched value.
       }


    }