Javascript Regexp test method weird behaviour

后端 未结 2 656
耶瑟儿~
耶瑟儿~ 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.

提交回复
热议问题