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?
CodePudding user response:
- 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,....
)
CodePudding user response:
The / around /someregex/ and the ' around 'some string' are both delimiters, which means they kind of do the same job - you don't need both.
Also, since you're using a string, you definitely need to escape the \ like you said.
Finally, RegExp.test expects a string, not a number, so you might want to convert it (although it casts it automatically in my browser, it's probably best to do it yourself with value.toString() or String(value) or something like that just to be sure).
All in all, something like
let value = 2.22;
const pattern = RegExp('^\\d \\.?\\d{0,2}$');
let result = pattern.test(value.toString()); // true
does the job.
