最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Dynamic regex pattern in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question asked Nov 6, 2014 at 13:46 JQuery MobileJQuery Mobile 6,30124 gold badges88 silver badges138 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 6

You 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}`)
发布评论

评论列表(0)

  1. 暂无评论