Dynamic Regex for min and max

Asked by At

Need to validate an input using Regular expression

  1. It should accept only digit
  2. Min and max should be dynamic

Thanks for your help in advance

My code is

min=3, max=10

MyRegex is

/^(\d{min, max})$/

2 Answers

0
Rafael On Best Solutions

I'd use a template string:

let min = 2;
let max = 4;

let r = new RegExp(`^\\d{${min},${max}}$`);

[
 '2',
 '1',
 '10',
 'aos',
 '3333',
 '33',
].forEach(s => console.log("%s\t: %s", s, r.test(s)));

0
Maheer Ali On

You can use template strings and RegExp constructor.

const test = (str,min,max) => new RegExp(`^\\d{${min},${max}}$`).test(str)
console.log(test('1234',2,4))