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

175
Visualizações
How can i make this code work properly, its based on a for-loop and is not completing its process
for (let i = 0; i < ans.length; i++) {
  ans = ans.replace(' ', '+');
  ans = ans.replace('  ', '+');
  ans = ans.replace('++', '+');
  //here ans is a value of an input.
}

Why is this stopping before completing the process?

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

0

Well based on the code I see you want to get rid of spaces no matter how many in a row, So I suggest Regular Expression :

let ans = "im an input here   so you can see the stuff"
ans = ans.replace(/\s+/g , '+'); \* im+an+input+here+so+you+can+see+the+stuff *\

How ever as it's been said on Wais Kamal Answer you can use replaceAll() as well for different cases

about 4 years ago · Juan Pablo Isaza Relatório

0

You are performing the same action in each iteration of the loop, so the loop is redundant in this code block. If you meant to replace all occurrences, a regex replacement is better:

ans = ans.replace(/ /g, '+');
ans = ans.replace(/  /g, '+');
ans = ans.replace(/\+\+/g, '+');

If you are only targeting modern browsers, you can use replaceAll instead:

ans = ans.replaceAll(' ', '+');
ans = ans.replaceAll('  ', '+');
ans = ans.replaceAll('++', '+');
about 4 years ago · Juan Pablo Isaza Relatório

0

Why is this stopping before completing the process?

To answer your only question, the loop ends prematurely because you write to ans variable and therefore you change the length of ans variable (that is used as condition in the for loop). So if you shorten its length, the loop stops earlier (as the new length is not reflected).

But check others answers on how to write it better.

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