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

116
Visualizações
Title Case a Sentence using for loop

I am so close in completing this exercise. The instruction is to convert the str into this new string Here Is My Handle Here Is My Spout.

My code is returning exactly Here Is My Handle Here Is My Spout but when I tried to console.log(result.split(" ")) it was returning with this [ '', 'Here', 'Is', 'My', 'Handle', 'Here', 'Is', 'My', 'Spout' ] .

I am trying to get rid of the empty string in the index 0 but I can't seem to remove it. I am also thinking that I am returning the arrays of the words when I passed it in the result instead of a string?

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
let firstCap = word.replace(word[0], word[0].toUpperCase());
 result = result + " " + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The problem is with the line:

result = result + " " + firstCap;

When result has value "" you should not add a space but rather an empty string as follows:

result = result + (result.length ? " " : "") + firstCap;

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
    let firstCap = word.replace(word[0], word[0].toUpperCase());
    result = result + (result.length ? " " : "") + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

A better approach would be to use Array#map() followed by Array#join().

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  return words.map(word => word.replace(word[0], word[0].toUpperCase())).join(" ");
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

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