Javascript Regexp test method weird behaviour

后端 未结 2 641
耶瑟儿~
耶瑟儿~ 2020-12-21 06:09

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

相关标签:
2条回答
  • 2020-12-21 06:37

    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.

    0 讨论(0)
  • 2020-12-21 06:43

    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

    0 讨论(0)
提交回复
热议问题