Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda