Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is JavaScript test() saving state in the regex? [duplicate]

Open up a browser console and execute the following code:

var foo = /foo/g;

Then,

foo.test("foo") // true

Then,

foo.test("foo") // false

If you continue to execute foo.test("foo"), you will see alternating true/false responses as if the var foo is actually being modified.

Anyone know why this is happening?

like image 536
Gregory Mazurek Avatar asked Mar 07 '13 16:03

Gregory Mazurek


People also ask

What is the purpose of the regex method test ()?

RegExp.prototype.test() The test() method executes a search for a match between a regular expression and a specified string. Returns true or 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.

How does JavaScript regex work?

Regular expressions are a sequence of characters that are used for matching character combinations in strings for text matching/searching. In JavaScript, regular expressions are search patterns (JavaScript objects) from sequences of characters. RegExp makes searching and matching of strings easier and faster.

What is test in JavaScript?

The test() method is a regular expression method. It searches a string for a pattern, and returns true or false, depending on the result. If it encountered the given pattern it returns true, else returns false.


2 Answers

Yes, that's how .test() and .exec() work when the regex is g global. They start at the end of the last match.

You can observe the current last index on the regular expression object using the .lastIndex property.

It's a writeable property, so you can reset it to 0 when/if you need. When the regex is run without finding a match, it automatically resets to 0.

like image 76
the system Avatar answered Sep 24 '22 16:09

the system


The regex keeps the position of the last test. This allows searching of long strings. You can reset this by setting lastIndex = 0;

like image 34
QuentinUK Avatar answered Sep 20 '22 16:09

QuentinUK