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

199
Vistas
Switch statement for RegExp falling to default?

In this switch statement, why does it fail in the regex check and falls to the default case?

The regex matches when I do it as if ... else, but, it doesn't matches when I do it as a switch statement and it falls to the default case!

let siteUrl = 'http://example.com';
let check1 = checkSite(siteUrl);
let check2 = checkSite();

function checkSite(siteUrl) {
    let url = (siteUrl) ? siteUrl : 'http://example.com';
    let regex = /^http:\/\/example\.com$/gi;
    let result = {};

    if (regex.test(url)) {
        console.log('regex match!');
    } else {
        console.log('regex does NOT match!');
    }
    
    switch (true) {
        case regex.test(url) : //<-- Why this fails?
            console.log('case 1'); 
            result.case = 1;
            break;
            
        case /another-regex/.test(url) :
            console.log('case 2');
            result.case = 2;
            break;
                        
        default : //<-- Why do I get here?
            console.log('default');
            result.case = 3;
    }
    console.log(result);
    return result;
}

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can alternatively use match instead and check if length is greater than 0. test seems to change even if you just log the value consecutively.

function checkSite(siteUrl) {
  let url = (siteUrl) ? siteUrl : 'http://example.com';
  let regex = /^http:\/\/example\.com$/gi;
  let result = {};

  if (url.match(regex)) {
    console.log('regex match!');
  } else {
    console.log('regex does NOT match!');
  }

  switch (true) {
    case url.match(regex).length > 0 : //<-- this will match
      console.log('case 1'); 
      result.case = 1;
      break;

    case url.match(/another-regex/).length > 0 :
      console.log('case 2'); 
      result.case = 2;
      break;
          
    default : 
      console.log('default');
      result.case = 3;
  }
  console.log(result);
  return result;
}

let siteUrl = 'http://example.com';
let check1 = checkSite(siteUrl);
let check2 = checkSite();

about 4 years ago · Juan Pablo Isaza Denunciar

0

Note that when you remove your if check the code works as expected:

let siteUrl = 'http://example.com';
let check1 = checkSite(siteUrl);
let check2 = checkSite();

function checkSite(siteUrl) {
    let url = (siteUrl) ? siteUrl : 'http://example.com';
    let regex = /^http:\/\/example\.com$/gi;
    let result = {};
    
    switch (true) {
        case regex.test(url) : //<-- Why this fails?
            console.log('case 1'); 
            result.case = 1;
            break;
            
        case /another-regex/.test(url) :
            console.log('case 2');
            result.case = 2;
            break;
                        
        default : //<-- Why do I get here?
            console.log('default');
            result.case = 3;
    }
    console.log(result);
    return result;
}

This is because when you store a RegExp to a variable, it stores state.

let regex = /^http:\/\/example\.com$/gi;
const url = "http://example.com";

for (let i = 0; i < 10; i++) {
  console.log(regex.test(url));
}

Per MDN:

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).

When a regex has the global flag set, test() will advance the lastIndex of the regex. (RegExp.prototype.exec() also advances the lastIndex property.)

Further calls to test(str) will resume searching str starting from lastIndex. The lastIndex property will continue to increase each time test() returns true.

Note: As long as test() returns true, lastIndex will not reset—even when testing a different string!

When test() returns false, the calling regex's lastIndex property will reset to 0.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try like this.

    switch (true) {
        case url.match(regex) :
            console.log('case 1'); 
            result.case = 1;
            break;
            
        case url.match(another-regex) :
            console.log('case 2');
            result.case = 2;
            break;
                        
        default :
            console.log('default');
            result.case = 3;
    }

Hope, it works!! XD

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