Does anyone has an explanation why this regular expression test returns false in the browser’s console?
In the screenshot above, I create a regex (first line), then test it against a string that should match, but,oddly enough, the test returns false (second line).
What’s strange is that the test returns "true" as long as I don’t press "Enter" (third line).
Regards,
Cyrille
2
Answers
JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).
Source from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
The behavior you’re observing is due to the way the global (g) flag affects the regular expression’s lastIndex property in JavaScript.
When you create a regular expression with the global flag (g), the RegExp object keeps track of the position of the last match using the lastIndex property. This property allows the regular expression to resume searching from where the last match ended, rather than starting over from the beginning of the string.
To avoid this behavior, you can either remove the global flag
alternative solution if you don’t need it or manually reset lastIndex to 0 before each test: