const digits = /\d+/g;
digits.test("Hello world! 123");
// true
digits.test("321"); // !!!!!!surprise
// false
digits.test("321");
// true
Wield right?
When a regex has the global flag set,
test()
will advance thelastIndex
of the regex. (RegExp.prototype.exec()
also advances thelastIndex
property.) 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
,lastIndex
will not reset—even when testing a different string!When
test()
returnsfalse
, the calling regex’slastIndex
property 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