Javascript Regexp test method weird behaviour

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

提交回复
热议问题