When a regex has the global flag set, test() will advance the lastIndex of the regex. (RegExp.prototype.exec() also advances the lastIndex property.)
Further calls to test(str) will resume searching str starting from lastIndex. The lastIndex property will continue to increase each time test() returns true.
Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!
When test() returns false, the calling regex's lastIndex property will reset to 0.
The following example demonstrates this behavior:
const regex = /foo/g; // the "global" flag is set
// regex.lastIndex is at 0
regex.test('foo') // true
// regex.lastIndex is now at 3
regex.test('foo') // false
// regex.lastIndex is at 0
regex.test('barfoo') // true
// regex.lastIndex is at 6
regex.test('foobar') //false
// regex.lastIndex is at 0
// (...and so on)
去掉
g
。有
g
的话,reg 是有状态的,会记住上次的匹配位置,影响后续匹配的行为。using test on regex with global flag: