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

134
Visualizações
Iterate over RegExp.exec(...)

From the RegExp.exec page on MDN, it gives the following example of iterating through a match with the g flag set:

const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

I have two questions about this code. The first one is why the !=== null is used here, why wouldn't the while loop be properly coded as:

while (array1 = regex1.exec(str1)) { // implicitly casts to boolean?
  console.log(`...`);

}

The above seems much more readable to me, but was wondering why the MDN docs used the first approach? Second, is it possible to declare and define the variable directly in the while loop? Something like:

while (let array1 = regex1.exec(str1)) { // don't need the `let array1` above?
  console.log(`...`);

}

Or is that not supported in the JS language?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Why the !== null is used here...?

True, in this case it is not needed. .exec() returns either an array or null, and since arrays are always truthy there is no need to explicitly compare with null.

Is it possible to declare and define the variable directly in the while loop?

No. If you want that, then turn to the for loop, which does support this:

for (let array1; array1 = regex1.exec(str1); null) {
  console.log(`...`);
}

This does indeed have the advantage that array1 has a more restricted scope. NB: I provided null to stress that the third part of the for header is intentionally unused.

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