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

120
Visualizações
Multiple RegEx not working with conditions

I'm trying to use two RegEx.test() methods with Logical AND in a conditional block, however, not getting expected result.

const mobileRegEx = /[0][4-5][0-9]{8}/g;
const firstPhone = '0432779680';
const secondPhone = '0543000987';


if(mobileRegEx.test(firstPhone)  &&  mobileRegEx.test(secondPhone)){
    console.log(firstPhone, secondPhone); /* expecting this to be executed but it is not */
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A regular expression with the g (global) flag keeps track of the position of the last match, and keeps searching from the next position.

So this means that the first match will return the position on the first number, and then the second match will fail because instead of restarting from the start it will start from the position of the first match and miss.

The fix is to simply remove the g from your original expression like this

/[0][4-5][0-9]{8}/;

However, I also see that your expression might give false positives. For example, if you add random characters before and after the actual number, it will still match.

E.g.

firstPhone = 'WRONG0432779680WRONG';

Will still return true. If you're using this for validating a phone number format, you need to restrict the regex to the whole string passed. You can do so by using ^ at the beginning and $ at the end, to say this is the whole string.

So the regex should look like

const mobileRegEx = /^[0][4-5][0-9]{8}$/;

Here's the final code

const mobileRegEx = /^[0][4-5][0-9]{8}$/;
const firstPhone = '0432779680';
const secondPhone = '0543000987';
if(mobileRegEx.test(firstPhone)  &&  mobileRegEx.test(secondPhone)){
    console.log(firstPhone, secondPhone);
}

about 4 years ago · Juan Pablo Isaza 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