RegExp中的lastIndex

  lastIndex用于标记由方法 RegExp.exec() 和 RegExp.test()找到的结果的下次检索的起始点,这样就可以通过反复调用这两个方法来遍历一个字符串中的所有匹配文本。但是前提是正则必须使用g才能使用,例如:

var str="The rain in Spain stays mainly in the plain";
var patt1=/ain/g;

while (patt1.test(str)==true)
{
  console.log("'ain' found. Index now at: "+patt1.lastIndex);
  // 'ain' found. Index now at: 8
  // 'ain' found. Index now at: 17
  // 'ain' found. Index now at: 28
  // 'ain' found. Index now at: 43
}
原文地址:https://www.cnblogs.com/jyybeam/p/13485390.html