Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda