[英]Dynamic regex pattern in JavaScript
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
.但是,我想用count
中的值替换正则表达式中的 1 。 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
.但是,现在,我总是为x
得到0
。
如果要使用动态构建的模式,则必须使用Regexp
对象:
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}}$`)
它为我工作
var alien = 'ajay'+' $%';
var all=new RegExp(`${alien}`)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.