-1

console.log(/^(\d{0,2}(\.\d{0,2})?)$/.test(22.22))

/^(\d{0,2}(\.\d{0,2})?)$/.toString() // "/^(\\d{0,2}(\\.\\d{0,2})?)$/"

const intergerDigitLimit = 2;
const decimalDigitLimit = 3;

console.log(new RegExp(`/^(\\d{0,${intergerDigitLimit}}(\\.\\d{0,${decimalDigitLimit}})?)$/`).test(22.23)); //false

This is my regular expression /^(\d{0,2}(\.\d{0,2})?)$/ I am trying to replace the digit limit dynamically with variable in JavaScript. So I did this /^(\d{0,2}(\.\d{0,2})?)$/.toString() to get the string format with all escape characters of expression so that I can change the value with a variable.

Output: /^(\\d{0,2}(\\.\\d{0,2})?)$/

Replacing with variable: `/^(\\d{0,${intergerLimit}}(\\.\\d{0,${decimalLimit}})?)$/`

Actual regular expression

/^(\d{0,2}(\.\d{0,2})?)$/.test(33.33) Output: true

Regular expression in string format

(new RegExp("/^(\\d{0,2}(\\.\\d{0,2})?)$/")).test(33.33) Output: false

Why it isn't working after escaping the backward slashes in string format? Can anyone help me with this issue ?

1 Answers1

0

You can create a regular expression in JavaScript with slashes, e.g.

/^(\\d{0,2}(\\.\\d{0,2})?)$/

or from a string without slashes

new RegExp("^(\\d{0,2}(\\.\\d{0,2})?)$").test(33.33)

But you can't combine both, slashes in a string.

Example:

console.log(new RegExp("/^(\\d{0,2}(\\.\\d{0,2})?)$/").test(33.33));
console.log(new RegExp("^(\\d{0,2}(\\.\\d{0,2})?)$").test(33.33));

Slashes in a string

console.log(new RegExp("/abc/").test('/abc/'));

are equivalent to actual slashes in a regular expression

/\/abc\//

Example:

console.log(new RegExp("/abc/").test('/abc/'));
console.log(new RegExp("/abc/").test('abc'));
console.log(new RegExp("abc").test('abc'));
console.log(/\/abc\//.test('/abc/'));
console.log(/\/abc\//.test('abc'));
console.log(/abc/.test('abc'));