3

I am using regular expression to check number of digits after decimal.

This is working fine when it is used for two or three digits, for example \d{2} or \d{3}, but what if I need to pass a variable instead of 2 and 3?

How do I pass a variable to the pattern? Is it possible?

2
  • You'd have to build the RegExp as a string. Commented Mar 1, 2012 at 9:15
  • could you please show me how to do that ,,,, how do i build that Commented Mar 1, 2012 at 9:17

4 Answers 4

3

You can use RegExp, like;


//just an example though
var i = 2;
var pattern = new RegExp("\\d{"+i+"}$");

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

2 Comments

Double backslash instead of one.
This worked for me var no=2; var rxDatePattern = new RegExp("^(?:\\d*\\.\\d{" + no + "})$");
1

You can write a function that generates the RegEx string with the parameter you provide for the number or decimal digits you need.

3 Comments

could you help me out with an example ,,,, as m relatively new to regular expressions
function getRegEx(int len) { return "\d{" + len + "}"; } and then you generate the RegEx with: reg_ex = getRexEx(6) to generate a RegEx to check for 6 decimal digits. You can't put variable in RegEx you need to create a string for them.
Thanks Odinn ,,, i understood your example..It helped me a lot..Thanks
0

What about just defining the range of the digits: \d{2,3}?

1 Comment

Something like this should work : var i=2, j=3, regex = new RegExp("^\\d{"+ i +","+ j +"}$", "g");
0

This might be useful : 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.