当前位置: 代码迷 >> Web前端 >> "g"在test、exed步骤中的对lastIndex的影响
  详细解决方案

"g"在test、exed步骤中的对lastIndex的影响

热度:101   发布时间:2012-11-23 22:54:33.0
"g"在test、exed方法中的对lastIndex的影响
//对于 test、exec方法,如果不使用'g'标志,多次执行,lastIndex都是0,否则,
//每一次执行以后,正则表达式都会记录lastIndex的位置,作为下次以匹配的开始位置。

var myRe=/d(b+)(d)/ig;
var str = "cdbBdbsbz";
/**
因为正则式使用 'g' 标志,myRe有一个属性lastIndex来记录下一次开始执行exec的开始位置(0-based).
因此,执行一次以后,lastIndex=5,即从str[5]开始执行检测。
如果没有添加 ‘g’标志,那么,每一次执行exec以后,lastIndex=0.即从头开始。
*/
var myArray = myRe.exec(str);
console.log(myArray);//输出:["dbBd", "bB", "d"]

myArray = myRe.exec(str);
console.log(myArray);//输出:null
  相关解决方案