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

98
Visualizações
Remove only the first unnecessary letter from a string

for learning purposes I want to remove only the FIRST letter 'a' from a string using a function. My function however removes ALL letters 'a' from the given string.

function removeFirstLetterA(str) {
  let letterA = 'a';
  for (let i = 0; i < str.length; i++) {
    if (str[i] === letterA) {
      str = str.replace(letterA, '');
    } 
}

return str;
}

Can anyone see my mistake and give any tips?

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

0

The mistake is that you don't stop when you come across and delete the first letter. Inside the if-block, you can break the loop, so that it won't continue after deleting the first one.

...
if (str[i] === letterA) {
  str = str.replace(letterA, '');
  break;
} 
...

Btw, you don't need a loop to delete the first match. Replace already does that. This would be enough:

function removeFirstLetterA(str) {
    return str.replace('a', '');
}
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