2

I am having a regex where i check the input is having 6 digit number. I am able to achieve it with the below refgex

/^\d{6}$/gm.test("123456")

I have used this regex in multiple places so I am trying to make it as a function

function testNumber(number, digitLength = 6){
  return /^\d{6}$/gm.test(number)
}

Now in some places the digitLength is of 3 and in some places its 4, now how can i interpolate the digitLength in the regex so i can pass as much the digitLength instead of hardcoding 6 in the regex.

Any help is appreciated

dev
  • 814
  • 10
  • 27
  • 4
    ```new RegExp(`^\\d{${digitLength}}$`, 'gm').test(number)``` – CherryDT Dec 10 '21 at 09:02
  • @CherryDT yep template literals would be easy but where to add so that why I am confused, without failing the regex – dev Dec 10 '21 at 09:05
  • so there is no way to interpolate variables inside regex string ? – dev Dec 10 '21 at 09:06
  • @CherryDT let me try and will update – dev Dec 10 '21 at 09:06
  • See also: [Use dynamic (variable) string as regex pattern in JavaScript](https://stackoverflow.com/questions/17885855/use-dynamic-variable-string-as-regex-pattern-in-javascript) – CherryDT Dec 10 '21 at 09:08
  • @CherryDT thanks it worked, if you can add an answer it will be helpful for future references for others – dev Dec 10 '21 at 09:10
  • It's essentially a duplicate that's why I didn't provide an answer because duplicates should be linked to the existing answer and closed and not answered separately. You should see a box above your question that asks you if the linked question's answers matched your question - you can just choose "yes" there to close this question. – CherryDT Dec 10 '21 at 09:12

2 Answers2

2

You are looking for (your regex):

function testNumber(number, digitLength = 6){
  return new RegExp(`^\\d{${digitLength}}$`, 'gm').test(number);
}

Refs: RegExp, Template literals.

Same, but optimized:
As @Thomas noticed, you don't need g flag in your case, because you always match global (full string), and you don't need m flag too, because you accept one-line inputs. So regex like this is enough:

function testNumber(number, digitLength = 6){
  return new RegExp(`^\\d{${digitLength}}$`).test(number);
}
Xeelley
  • 1,081
  • 2
  • 8
  • 18
2

Instead of a dynamic regex you could also do it like this:

function testNumber(number, digitLength = 6){
  return number.length === digitLength // check expected length
    && /^\d+$/.test(number);           // and that it is all digits
}
Thomas
  • 11,958
  • 1
  • 14
  • 23