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

195
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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