2

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})?$/
Tushar
  • 82,599
  • 19
  • 151
  • 169
Dora
  • 6,154
  • 10
  • 45
  • 88

2 Answers2

2

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:

Community
  • 1
  • 1
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
  • this is nice...never thought of extracting the max numbers out into variables. learned something new again... thx thx – Dora Dec 21 '16 at 12:25
0

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
Sahadev
  • 1,278
  • 4
  • 20
  • 38