const digits = /\d+/g;digits.test("Hello world! 123");// truedigits.test("321"); // !!!!!!surprise// falsedigits.test("321");// true
Wield right?
When a regex has the global flag set,
test()will advance thelastIndexof the regex. (RegExp.prototype.exec()also advances thelastIndexproperty.) Further calls to test(str) will resume searching str starting from lastIndex. The lastIndex property will continue to increase each time test() returns true.Note: As long as
test()returnstrue,lastIndexwill not reset—even when testing a different string!When
test()returnsfalse, the calling regex’slastIndexproperty will reset to0.
How?
Use String search or match instead.
"Hello world! 123".search(digits) > -1;// true"321".search(digits) > -1;// true"321".search(digits) > -1;// true
