JavaScript RegExp
s maintain state internally, including fields such as the last index matched. Because of that, you can see some interesting behavior when reusing a regex as in the example you give.
The /g
flag would cause it to return true
once for each successive match against the given string (of which there only happens to be one in your example), after which it would return false
once and then start all over again. Between each call, the aforementioned lastIndex
property would be updated accordingly.
Consider the following:
var str = "12";
var regex = /\d/g;
console.log(regex.test(str)); // true
console.log(regex.test(str)); // true
console.log(regex.test(str)); // false
Versus:
console.log(/\d/g.test(str)); // true
console.log(/\d/g.test(str)); // true
console.log(/\d/g.test(str)); // true
console.log(/\d/g.test(str)); // true
// ...and so on, since you're instantiating a new RegExp each time