I have a RegEx pattern to match a decimal number with 2 decimals places, i.e. /^\d+\.?\d{0,2}$/
For example the following returns true
const value=2.22;
let result = /^\d+\.?\d{0,2}$/.test(value);
console.log(`result ${result}`);
I would like to be able to build this for any decimal places, so I wanted to use RegExp so I could create a string and then pass to this. So I tried the following..
const pattern = new RegExp('/^\d+\.?\d{0,2}$/');
result = pattern.test(value);
console.log(`result ${result}`)
But this returns false. I have tried escaping the \, eg using '/^\\d+\\.?\\d{0,2}$/' but this does not work either.
I have this example here.
I would like to know how I can use this in the RegExp, is anyone able to help me here?
>Solution :
- A Regexp test needs to be testing a string
- You need to remove the
/from the RegExp string construction - You can use template literals to have variable decimals
- We need to escape the
\in\dand\.when using new RexExp
const matchDecimals = (num,decimals) => {
const pattern = new RegExp(`^\\d+\\.?\\d{0,${decimals}}$`);
console.log(pattern);
return pattern.test(String(num));
};
console.log(
matchDecimals(2.333,3),
matchDecimals(2.3333,3),
matchDecimals(2.000,3) // would fail if we had \d{1,....
)