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.
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.
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.
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.
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)
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