代码如下:
>var a=/\d+/g
undefined
>a.exec('a2a')
['2',index:1,input:'a2a']
>a.exec('a1a')
null
>/\d+/g.exec('a2a')
['2',index:1,input:'a2a']
>/\d+/g.exec('a1a')
['1',index:1,input:'a1a']
为什么第二次执行就会返回null而不是正确的
6 回复
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
If your regular expression uses the “g” flag, you can use the exec method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of str specified by the regular expression’s lastIndex property (test will also advance the lastIndex property). For example, assume you have this script:
var myRe = /ab*/g;
var str = "abbcdefabh";
var myArray;
while ((myArray = myRe.exec(str)) !== null)
{
var msg = "Found " + myArray[0] + ". ";
msg += "Next match starts at " + myRe.lastIndex;
console.log(msg);
}