Catalin
Catalin

Reputation: 11731

new RegExp is not working

I have a regular expression which validates 3 consecutive digits.

/^\d{3}$/.test("12345")  // false
/^\d{3}$/.test("123")    // true

How can I transform this regex pattern into a RegExp object?

I tried:

var re = new RegExp("\\d{3}", "gi");

but re.test("12345") returns true

What am I doing wrong?

Upvotes: 1

Views: 2120

Answers (4)

CD..
CD..

Reputation: 74176

var re = new RegExp("^\\d{3}$", "gi");

(I assume the "gi" flag is not really necessary in this case...)

http://jsfiddle.net/GyZqw/

Upvotes: 5

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

Use this regular expression:

^\d{3}$

with start and end of line specified.

In JavaScript you should escape \ char, i.e.:

"^\\d{3}$"

Upvotes: 2

julian0zzx
julian0zzx

Reputation: 263

new RegExp("^\\d{3}$", "gi")

you forgot ^ and $

Upvotes: 2

sblom
sblom

Reputation: 27353

var re = new RegExp("^\\d{3}$");

Upvotes: 1

Related Questions