Home > Back-end >  Title Case a Sentence using for loop
Title Case a Sentence using for loop

Time:03-10

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"));

CodePudding user response:

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"));

  • Related