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 ?