I have some code that matches a certain number of digits after a decimal. Currently, I have the following:
var input = getValueFromUser();
var count = getCount();
var x = Number(input.toString().match(/^\d+(?:\.\d{0,1})?/));
alert(x);
This approach always gets the first digit after the decimal. However, I want to replace the 1 in the regex with the value in count
. How do I do that? I tried the following:
var pattern = '/^\d+(?:\.\d{0,' + count + '})?/';
var x = Number(input.toString().match(pattern));
However, now, I always get 0
for x
.
I have some code that matches a certain number of digits after a decimal. Currently, I have the following:
var input = getValueFromUser();
var count = getCount();
var x = Number(input.toString().match(/^\d+(?:\.\d{0,1})?/));
alert(x);
This approach always gets the first digit after the decimal. However, I want to replace the 1 in the regex with the value in count
. How do I do that? I tried the following:
var pattern = '/^\d+(?:\.\d{0,' + count + '})?/';
var x = Number(input.toString().match(pattern));
However, now, I always get 0
for x
.
-
You have to use
Regexp
object if you want to use dynamic patterns – hindmost Commented Nov 6, 2014 at 13:48 -
BTW, isn't
\D
the same as^\d
? – Phil Tune Commented Nov 6, 2014 at 14:01
4 Answers
Reset to default 6You have to use Regexp
object if you want to use dynamically built patterns:
var re = new RegExp('^\\d+(?:\\.\\d{0,' + count + '})?');
This will help you.
var pattern = '^\\d+(?:\\.\\d{0,' + '5' + '})?',
reg=new RegExp(pattern),
x = Number(input.toString().match(reg));
mask: new RegExp(`^[a-zA-Z0-9]{0,${maxLength}}$`)
its work for me
var alien = 'ajay'+' $%';
var all=new RegExp(`${alien}`)