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})?$/
1
  • You may consider using <input type="text" pattern="\d{1,7}(\.\d{2})?" /> Commented Dec 21, 2016 at 11:50

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

1 Comment

this is nice...never thought of extracting the max numbers out into variables. learned something new again... thx thx
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

1 Comment

Ok i got your point just pass limits into variable and append with pattern into RegExp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.