This case is an Error?
execut in firebug
altern = /raeeoCott/ig //
for(var h = 0; h<3; h++)
for(var i = 0; i<5; i++)
if(altern.test('raeeocott'))
console.log('ddd')
h=1 :: (8 true); ?????
// 5 * 3 = 15 != 8
why is this happening?
This case is an Error?
execut in firebug
altern = /raeeoCott/ig //
for(var h = 0; h<3; h++)
for(var i = 0; i<5; i++)
if(altern.test('raeeocott'))
console.log('ddd')
h=1 :: (8 true); ?????
// 5 * 3 = 15 != 8
why is this happening?
It's happening because you included the g
flag on your regular expression. That flag preserves state between calls to .test()
. After a successful match, the next attempt will be to attempt the match on the remainder of the source string, and the match will fail. So you get 8 successful matches, interspersed with failures.
The first call to .test()
succeeds. The regular expression object "remembers" that it's supposed to start after the end of the matched string, which will be the very end of the source string. That won't match on the next iteration, but because that attempt used up the end of the source string, the regular expression resets to position 0. The next try, then, will succeed, and over and over like that.
Short version: get rid of the g
flag.