What is wrong with this regex when I use global flags and case insensitive flags? Queries are user-generated input. The result should be [true, true].
var query = 'Foo B'; var re = new RegExp(query, 'gi'); var result = []; result.push(re.test('Foo Bar')); result.push(re.test('Foo Bar')); //The result will be [true, false]
var reg = /^a$/g; for(i = 0; i < 10;) console.log(reg.test("a"));
You are using a
RegExpobject and executing it multiple times. On each execution, it continues from the last matching index.Before each execution, you need to "reset" the regex to start from scratch:
result.push(re.test('Foo Bar')); re.lastIndex = 0; result.push(re.test('Foo Bar')); // 现在的结果是 [true, true]Having said that, it might be more readable to create a new RegExp object each time (the overhead is minimal since the RegExp is already cached):
Using a
RegExpobject with thegflag will keep track of thelastIndexwhere the match occurred, so on subsequent matches it will Start from the last used index, not from 0. Take a look at the example:var query = 'Foo B'; var re = new RegExp(query, 'gi'); console.log(re.lastIndex); console.log(re.test('Foo Bar')); console.log(re.lastIndex); console.log(re.test('Foo Bar')); console.log(re.lastIndex);