I found in my code funny issue. Here is simplified version of my code. Calling regex.test
changes its output value each time you call that. You can try to do that in devtools with 'evaluation on select' and it will show you different values.

- 1,624
- 1
- 23
- 57
-
Does this answer your question? [Why does a RegExp with global flag give wrong results?](https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results) – Mr Lister Jul 30 '22 at 13:00
1 Answers
The issue is that you are using /g
in your Regexp - when this is used, and the regex is executed multiple times, it will always begin where it left off last time.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex
This property is set only if the regular expression instance used the "g" flag to indicate a global search. The following rules apply:
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.
You can verify this by doing console.log(regex.lastIndex)
in your loop:
for (var a = 0; a < 10; a++) {
console.log(regex.lastIndex)
if (!regex.test(inner)) {
log.innerHTML += "true";
}
else {
log.innerHTML += "false";
}
log.innerHTML += " ";
}
And you will see it alternates between 0 18. So, when it starts at 0, it matches, when it starts at 18, it doesn't match.