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.

2
  • You have to use Regexp object if you want to use dynamic patterns Commented Nov 6, 2014 at 13:48
  • BTW, isn't \D the same as ^\d? Commented Nov 6, 2014 at 14:01

4 Answers 4

6

You have to use Regexp object if you want to use dynamically built patterns:

var re = new RegExp('^\\d+(?:\\.\\d{0,' + count + '})?');
Sign up to request clarification or add additional context in comments.

1 Comment

Note that the backslashes in the string need to be escaped (unlike backslashes in a regex literal).
0

This will help you.

var pattern = '^\\d+(?:\\.\\d{0,' + '5' + '})?',
    reg=new RegExp(pattern),
    x = Number(input.toString().match(reg));

1 Comment

Don't include the / at the beginning and end of the regex pattern if supplying it as a string - that's for regex literals only. Also if the pattern is in a string you need to escape the backslashes.
0

mask: new RegExp(`^[a-zA-Z0-9]{0,${maxLength}}$`)

its work for me

Comments

0
var alien = 'ajay'+' $%';
var all=new RegExp(`${alien}`)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.