Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: How to convert pattern to string for RegExp

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

  1. A Regexp test needs to be testing a string
  2. You need to remove the / from the RegExp string construction
  3. You can use template literals to have variable decimals
  4. We need to escape the \ in \d and \. 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,....
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading