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

Rafael On Best Solutions

I'd use a template string:

let min = 2;
let max = 4;

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

].forEach(s => console.log("%s\t: %s", s, r.test(s)));

Maheer Ali On

You can use template strings and RegExp constructor.

const test = (str,min,max) => new RegExp(`^\\d{${min},${max}}$`).test(str)