I've been wrestling with this all day, and I can't figure out if I'm doing something wrong or if I've found a bug in Chrome's JavaScript engine. It appears that consecutive calls to a RegExp
object with the global flag returns inconsistent results for the same input string. I'm testing with the following function:
function testRegex(pattern, array) {
document.writeln('Pattern = ' + pattern + ', Array = ' + array + '<br/>');
for (var ii = 0; ii < array.length; ii++) {
document.writeln(ii + ', ');
document.writeln(array[ii] + ', ');
document.writeln(pattern.test(array[ii]) + '<br />');
}
document.writeln('<br/>');
}
When I call the function with /a/g
as the pattern and various arrays of strings, I get the following results, many of which are incorrect as far as I can tell:
// EXPECTED: True
// ACTUAL: True
testRegex(/a/g, ['a']);
// EXPECTED: True, True
// ACTUAL: True, False
testRegex(/a/g, ['a', 'a']);
// EXPECTED: True, True, True
// ACTUAL: True, False, True
testRegex(/a/g, ['a', 'a', 'a']);
// EXPECTED: True, False, True
// ACTUAL: True, False, True
testRegex(/a/g, ['a', 'b', 'a']);
// EXPECTED: True, True, True, True
// ACTUAL: True, False, True, False
testRegex(/a/g, ['a', 'a', 'a', 'a']);
// EXPECTED: True, False, False, True
// ACTUAL: True, False, False, True
testRegex(/a/g, ['a', 'b', 'b', 'a']);
When I call the same function with the same arrays of strings, but pass /a/
as the pattern, the actual results all match the expected results.
// EXPECTED: True
// ACTUAL: True
testRegex(/a/, ['a']);
// EXPECTED: True, True
// ACTUAL: True, True
testRegex(/a/, ['a', 'a']);
// EXPECTED: True, True, True
// ACTUAL: True, True, True
testRegex(/a/, ['a', 'a', 'a']);
// EXPECTED: True, False, True
// ACTUAL: True, False, True
testRegex(/a/, ['a', 'b', 'a']);
// EXPECTED: True, True, True, True
// ACTUAL: True, True, True, True
testRegex(/a/, ['a', 'a', 'a', 'a']);
// EXPECTED: True, False, False, True
// ACTUAL: True, False, False, True
testRegex(/a/, ['a', 'b', 'b', 'a']);
I've created a working example of the code above: http://jsfiddle.net/FishBasketGordo/gBWsN/
Am I missing something? Shouldn't the results be the same for the given arrays of strings no matter if the pattern is global or not? Note, I've primarily been working in Chrome, but I've observed similar incorrect results in Firefox 4 and IE 8.