Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
adding dynamic values to regex

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

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

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
}
about 4 years ago · Santiago Gelvez Relatório

0

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);
}
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda