Malcolm Dew-Jones wrote: > Brantley Harris wrote: > : Type this into your javascript console, you'll notice it > : prints out > : false. > : r = new RegExp("\\\\", "g"); r.test('\\') == r.test('\\');
> : What is going on here?
> This part is easy. What you show below is that each /g test > alternates true and false, so "r.test('\\') == r.test('\\'); > " is true==false, which is certainly false.
> So the only question is why r.test('\\') alternates true and false.
<snip>
Regular expression objects have a - lastIndex - property that receives different handling depending on whether the regular expression has its - global - flag set to true or false. With the - global - flag set to true the regular expression's - exec - method (which is employed by its - test - method) does not re-set the - lastIndex - to zero unless it is already greater than the length of the string being tested. The - lastIndex - property is used to determine the point in the tested string at which a test starts. Thus - exec - starts testing the second time after the point at which the match was found in the first test. That second test fails, leaving the - lastIndex - greater than the length of the tested string, so a third test sees the - lastIndex - re-set it to zero. The result is oscillating behaviour described.
This characteristic allows for constructs such as applying a global regular expression in the condition of a - while - loop and handling each match in the body of the loop, and so can be useful. It becomes problematic when the - global - flag is employed inappropriately, though it is trivial to manually set/re-set the regular expression's - lastIndex - property to zero prior to using it.