Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 647
Priyank Patel Avatar asked Sep 29 '26 11:09

Priyank Patel


2 Answers

You can use RegExp, like;


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

like image 198
Sudhir Bastakoti Avatar answered Oct 02 '26 01:10

Sudhir Bastakoti


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

like image 39
Odinn Avatar answered Oct 02 '26 00:10

Odinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!