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

210
Visualizações
global Regexp is returning incorrect index inside for loop

I am trying to remove a timestamp (formatted as numbers dash numbers) from a string. In the process I experimented with global RegExp. I came up with the following code:

for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
  let s=filename.split("_")
  let globalRegex = new RegExp('^\d+\-\d+$', 'g');
  for(let si of s){
    if(globalRegex.test(si)) break
  }
  console.log(`match found at: `,globalRegex.lastIndex)
}

which returns:

match found at:  0
match found at:  0

My questions are:

  1. How do I correctly remove the timestamp from the string?
  2. Why is the regexp returning 0 for both runs?
  • I expected (0 then 3 index to be returned) It seems like the state of the global regex isnt being reinitialized for the second run. However I assumed it would be, since it is redeclared inside the for loop
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are quite a few issues here:

  • You get 0s because your regex does not match, and it does not match because you defined the regex string inside a regular string literal, thus, losing all single backslashes. The pattern must be set with a regex literal, let globalRegex = /^\d+\-\d+$/; (see Why this javascript regex doesn't work?). Note the absence of the g flag, if you use it with RegExp#test(), you must not use g flag to avoid issues (see Why does a RegExp with global flag give wrong results?).
  • Even if you define the regex properly you will get 0s as output because a /^\d+\-\d+$/ regex can and will only match at the start of the string (Index=0). You seeem to want to get the IDs of the "words" or "tokens" in the string, so you need to count them.

So, you could re-write the code as

for(let filename of ["123-123_aaa_bbb_ccc","aaa_bbb_ccc_129-999"])
{
  let result = -1;
  let s=filename.split("_")
  let globalRegex = /^\d+\-\d+$/;
  for (const [index, si] of s.entries()) {
    if(globalRegex.test(si)) {
        result = index
        break
    }
  }
  console.log(`match found at: `, result)
}

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