I\'ve been trying evaluate a string based in a regular expression, however I noticed a weird behaviour and when I test with the regular expression more than once. The test m
From the MDN documentation:
As with
exec()
(or in combination with it),test()
called multiple times on the same global regular expression instance will advance past the previous match.
So, the second time you call the method, it will look for a match after the first match, i.e. after +56982249953
. There is no match because the pattern is anchored to the start of the string (^
) (and because there are no characters left), so it returns false
.
To make this work you have to remove the g
modifier.
That's because the test
method, like many RegExp
methods, tries to find multiple matches in the same string when used with the g
flag. To do this, it keeps track of position it should search from in the RegExp's lastIndex
property. If you don't need to find multiple matches, just don't put the g
flag. And if you ever want to use it, just remember to set regex.lastIndex
to 0 when you want to test a new string.
Read more about lastIndex on MDN