JS-RegExp-LastIndex-Effects
# Amazing RegExp Test Function
var regex = /foo/g;
regex.test('foo'); // true
regex.test('foo'); // false
2
3
And Why this?
# What MDN said
If the regex has the global flag set, test() will advance the lastIndex of the regex. A subsequent use of test() will start the search at the substring of str specified by lastIndex (exec() will also advance the lastIndex property). It is worth noting that the lastIndex will not reset when testing a different string.
The key world is "global" flag set and un-reset lastIndex after test a string.
# How to avoid
- use regexp as sting
/foo/g
- do not use
g
flag - if use RegExp object, should clone object every time.
_.cloneDeep(regexp).test
# Why RegExp use lastIndex property when global mode.
When use 'g' flag, it is mean use sticky search.
The fellow roles will effect lastIndex after test
or exec
called.
If lastIndex is greater than the length of the string, test() and exec() fail, then lastIndex is set to 0. If lastIndex is equal to the length of the string and if the regular expression matches the empty string, then the regular expression matches input starting at lastIndex. If lastIndex is equal to the length of the string and if the regular expression does not match the empty string, then the regular expression mismatches input, and lastIndex is reset to 0. Otherwise, lastIndex is set to the next position following the most recent match.
# Reference
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test#Using_test()_on_a_regex_with_the_global_flag https://www.ecma-international.org/ecma-262/6.0/#sec-regexpbuiltinexec