简体   繁体   中英

JavaScript: How to convert pattern to string for RegExp

I have a RegEx pattern to match a decimal number with 2 decimals places, ie /^\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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM