Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.test() is giving true false sequential?

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.

like image 774
Amit Thakkar Avatar asked Jun 17 '15 09:06

Amit Thakkar


People also ask

What does RegExp test do?

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.

Which is faster RegExp match or RegExp test?

Use . test if you want a faster boolean check. Use . match to retrieve all matches when using the g global flag.

Why * is used in regex?

- a "dot" indicates any character. * - means "0 or more instances of the preceding regex token"

How do I check if a string is in regular expressions?

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.


1 Answers

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.

like image 84
Benjamin Gruenbaum Avatar answered Oct 02 '22 19:10

Benjamin Gruenbaum