Wrong Results from Regexp with Global Flag
In the provided code, the regular expression new RegExp(query, 'gi') is used with both the g (global) and i (case insensitive) flags. However, the result is unexpected: [true, false].
Understanding the Global Flag
The g flag in a RegExp object controls the behavior of the test() method. When set, test() searches for the pattern in the string repeatedly, starting from where the previous match ended. This is known as "stickiness."
Incorrect Result Explanation
In the example, the first call to re.test('Foo Bar') finds the match "Foo B." Since the g flag is set, lastIndex is updated to the position after "Foo B." This means the subsequent call to re.test('Foo Bar') starts searching from the position after "Foo B." No match is found, leading to the false result.
Example with Sticky Flag
Consider the following code:
var reg = /^a$/g; for(i = 0; i++ < 10;) console.log(reg.test("a"));
This code prints "true" 10 times. Since reg has the g flag, it sticks to the last match, repeatedly testing "a" from the position after the previous match until the end of the string.
Solution
To fix the original code, reset re.lastIndex to 0 before each test() call:
var query = 'Foo B'; var re = new RegExp(query, 'gi'); result.push(re.test('Foo Bar')); re.lastIndex = 0; result.push(re.test('Foo Bar'));
This ensures that the search starts from the beginning of the string for each test() call, yielding the correct result of [true, true].
The above is the detailed content of Why Does a Global Regexp's `test()` Method Return Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!