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.
JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.
Use . test if you want a faster boolean check. Use . match to retrieve all matches when using the g global flag.
- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"
If you need to know if a string matches a regular expression RegExp , use RegExp.prototype.test() . If you only want the first match found, you might want to use RegExp.prototype.exec() instead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With