P粉3990907462023-08-23 00:35:02
You are using a RegExp
object 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):
result.push((/Foo B/gi).test(stringA)); result.push((/Foo B/gi).test(stringB));
P粉5233350262023-08-23 00:21:13
Using a RegExp
object with the g
flag will keep track of the lastIndex
where 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);