Regex Experssion

let userCheck = /^[A-Z]{2.}\d*$/gi;

When I run this code in console, I get false first, and when I again rerun this code I get the result true. Why does it happen? It has caused me a lot of trouble.

Quoting from MDN article for test:

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.

Essentially the reason for different results when running the same thing twice comes from this reason

Worth noting that you’ve got a full stop ( . ) in the braces rather than a comma ( , )

1 Like