8

Anyone can explain me, why local Regex variable and non local Regex variable have different output.

var regex1 = /a|b/g;
function isAB1() {
    return regex1.test('a');
}
console.log(isAB1()); // true
console.log(isAB1()); // false
console.log(isAB1()); // true
console.log(isAB1()); // false


function isAB2() {
    var regex2 = /a|b/g;
    return regex2.test('a');
}
console.log(isAB2()); // true
console.log(isAB2()); // true
console.log(isAB2()); // true
console.log(isAB2()); // true

I have created a JSFiddle for the same here.

Amit Thakkar
  • 687
  • 1
  • 5
  • 14
  • 1
    from the [doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) : `called multiple times on the same global regular expression instance will advance past the previous match`. – Hacketo Jun 17 '15 at 09:32

1 Answers1

8

You gave your regex the g flag which means it will globally match results. By doing so you explicitly asked your regex to keep state about its previous matches.

var regex1 = /a|b/g;

> regex1.lastIndex
0
> regex1.test('a');
true
> regex1.lastIndex
1
> regex1.test('a');
false

If you remove the g you will get the results you were expecting.

You can check your expressions .lastIndex property for when it is done matching.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504