I am trying to do some pattern matching using regular expression in NodeJS, and stuck with a weird problem. The pattern matching fails for the third call for the same pattern and with the same string used for matching the pattern. Below is the code snippet which I am trying.
var iOSRegex = /iPad|iPhone|iPod/g;
var ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1";
var first = iOSRegex.test(ua);
var second = iOSRegex.test(ua);
var third = iOSRegex.test(ua); // This evaluates to false.
console.log(first + ' -- ' + second + ' -- ' + third);
//Result true -- true -- false
As you can see the third check on line 6 fails. I tested this on Chrome and Safari browser consoles, which produces the exact same result.
Interesting part is that this fails when we call test one after the other 3 times and the third call always fails. The below given code proves this behavior.
var iOSRegex = /iPad|iPhone|iPod/g;
var ua = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B137 Safari/601.1";
var first = iOSRegex.test(ua);
console.log(ua.match(iOSRegex));
var second = iOSRegex.test(ua);
var third = iOSRegex.test(ua);
var fourth = iOSRegex.test(ua); // This evaluates to false.
console.log(first + ' -- ' + second + ' -- ' + third + ' -- ' + fourth);
/*
Result
[ 'iPhone', 'iPhone' ]
true -- true -- true -- false
*/
But I have a NodeJS application and I have defined the above the regex as a constant. Due to this behavior every third request from an iPhone evaluates this to false and thus failing to detect it as an iOS device. What could be wrong