Green
Green

Reputation: 30805

The same RegExp returns true and false alternatively. Why?

I have this regexp. And it returns true and false interchangeably. How it can be? How to fix the regexp? The goal is to "allow figures AND spaces only" (123 56 123).

var r = new RegExp("[0-9\s]{3,30}", "gi")
r.test("123454")
true
r.test("123454")
false

Upvotes: 2

Views: 125

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174706

You need to use an anchored regex and also escape the backslash one more time. And don't use g modifier since the regex is anchored.

var r = new RegExp("^[0-9\\s]{3,30}$", "m")

Example:

> var r = new RegExp("^[0-9\\s]{3,30}$", "m")
undefined
> r.test("123454")
true
> r.test("123454")
true

OR

> var r = /^[0-9\s]{3,30}$/m;
undefined
> r.test("123454")
true

Upvotes: 2

anubhava
anubhava

Reputation: 785256

Problem is use of global g flag which causes internal state (lastIndex property) of RegExp object to be remembered across multiple invocations of test or exec methods..

If you use take out g flag from your regex i.e.:

var r = new RegExp("[0-9\\s]{3,30}");

Then it will behave fine.

r.test("123454")
true
r.test("123454")
true
r.test("123454")
true

PS: i flag has no use and that can be removed as well.

Upvotes: 3

Vladu Ionut
Vladu Ionut

Reputation: 8193

try this regex https://regex101.com/r/jO0sX7/1

^[0-9\s]{3,30}$

or

^[\d\s]{3,30}$

Upvotes: 1

Related Questions