Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does my javascript regex.test() give alternating results [duplicate]

Possible Duplicate:
Javascript regex returning true.. then false.. then true.. etc

var r = /\d/g; var a = r.test("1"); // will be true var b = r.test("1"); // will be false console.log(a == b); // will be false 

Please explain to me why the result of r.test("1") alternates with each call?

I was able to work around the issue I was having by removing the g modifier. However I would still like to understand why this happens.

like image 608
Dennis George Avatar asked May 17 '10 17:05

Dennis George


People also ask

What does regex test do in JavaScript?

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.

What does the G flag do regex?

The " g " flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global (" g ") and sticky (" y ") will ignore the global flag and perform sticky matches. You cannot change this property directly.

What is the difference between match and test in JavaScript?

match() is a method on a string and takes a regex object as an argument. . test() returns a boolean if there's a match or not. It does not return what actually matches.


1 Answers

When you're using /g, the regex object will save state between calls (since you should be using it to match over multiple calls). It matches once, but subsequent calls start from after the original match.

(This is a duplicate of Javascript regex returning true.. then false.. then true.. etc)

like image 156
pkh Avatar answered Oct 16 '22 19:10

pkh