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

119
Visualizações
RegExp.prototype.exec() can loop forever

Steps to reproduce:

  • Open the MDN docs page: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec.
  • Open 'Developer Tools' and switch to the Console tab.
  • Replace foo* with .* on the docs page and click 'Run' button.

This will result in an infinite loop. How do I prevent this from happening? In my Node application, the user can specify .* as the pattern and it hangs. I do not think doing a string-match and preventing this specific regex pattern would help as there might be many other patterns that will result in an infinite loop.

Source code (in case the content of the MDN page changes):

const regex1 = RegExp('.*', 'g');
const str1 = 'text';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(array1.index);
}
almost 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You could add a check that the lastIndex property of the regex has changed, and if it hasn't (indicating a zero-length match, which would then loop infinitely), break out of the loop:

const regex1 = RegExp('.*', 'g');
const str1 = 'text';
let array1;
let lastIndex = 0;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(array1);
  if (regex1.lastIndex == lastIndex) break;
  lastIndex = regex1.lastIndex;
}

Note you can put the test before doing anything with the result of the exec, depending on whether you want to capture the zero-length match or not.

almost 4 years ago · Santiago Trujillo Relatório

0

All patterns that can match an empty string exhibit this behaviour - see Regex that can match empty string is breaking the javascript regex engine or Zero-Length regexes and infinite matches?.

The simple solution would be to just use matchAll instead testing for some complicated loop condition yourself:

const regex = /.*/g;
const str = 'text';
for (const match of str.matchAll(regex)) {
  console.log(match.index, match[0]);
}

Alternatively, using str.match(regex) instead of regex.exec(str) would also help.

almost 4 years ago · Santiago Trujillo 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