Priyank Patel
Priyank Patel

Reputation: 6996

Regular Expression Pattern With A Variable

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?

Upvotes: 3

Views: 1886

Answers (4)

ZZ-bb
ZZ-bb

Reputation: 2167

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

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

You can use RegExp, like;


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

Upvotes: 3

Odinn
Odinn

Reputation: 808

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

Upvotes: 1

Related Questions