Dora
Dora

Reputation: 6970

How can I make this RegEx into JavaScript RegExp object?

I have this RegEx which allows people to input max 7 digits before decimal and two after which is optional.

I figure it would be neater to put them into a variable. I have searched through with people saying use the RegExp object but I am still confused how it's done.

This is what I have with my RegEx.

/^(\d{1,7})(\.\d{2})?$/

Upvotes: 2

Views: 29

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626754

You can use the following code:

var max1 = 7;
var max2 = 2;
var rx = new RegExp("^(\\d{1," + max1 + "})(\\.\\d{" + max2 + "})?$");
console.log(rx.test("1234567.12"));
console.log(rx.test("1234567.123"));
console.log(rx.test("12345678.12"));

Also, check these posts:

Upvotes: 2

Sahadev
Sahadev

Reputation: 1448

you can use:

var patt = new RegExp(/^(\d{1,7})(\.\d{2})?$/);

How to test:

console.log(patt.test('1234567ab')) : false

console.log(patt.test('1234567.12')) : true

Upvotes: 0

Related Questions