javascript – Why does a RegExp with global flag give wrong results?
You are using a single RegExp object and executing it multiple times. On each successive execution it continues on from the last match index.
You need to “reset” the regex to start from the beginning before each execution:
result.push(re.test('Foo Bar'));
re.lastIndex = 0;
result.push(re.test('Foo Bar'));
// result is now [true, true]
Having said that it may be more readable to create a new RegExp object each time (overhead is minimal as the RegExp is cached anyway):
result.push((/Foo B/gi).test(stringA));
result.push((/Foo B/gi).test(stringB));
Read more here: Source link
