Javascript basic algorithm challenge - Title Case a Sentence

Hello campers

I’ve been doing the Javascript basic algorithm challenge and got stuck on the title case a sentence… And I can not understand why my script is not working… Please enlighten me.

function titleCase(str) {
  // Declare an array to store the passed and splited string argument
  var strSplit = [];
  strSplit = str.split(" ");

  // Declare an array where capitalized strings will be stored
  var strUpperCase = [];

  // Declare a number i for the loop function below
  var i = 0;

  // Loop function to iterate through the strSplit array and capitalize each entry
  while (i <= strSplit.length - 1, i++) {
    strUpperCase.push(strSplit[i].charAt(0).toUpperCase());
  }
    
  // Declare an array to join the capitalized strings
  var strJoin = strUpperCase.join(" ");
  return strJoin;
  
}

console.log(titleCase("I'm a little tea pot"));

I found that the array strUpperCase does not get any entries at all. i.e. push function didn’t work, resulting the array to be empty. And the capitalisation part didn’t work neither… I’m not sure what my fault was here… Please help.

Other than fixing the loop, you’re definitely on the right track with your logic. Just be aware that your algorithm will need just a little tweaking at the beginning to account for all the other cases.

1 Like

Thanks as always Randell!

The loop is indeed working now. But just as welshl123 has suggested below. I have to figure out a way to take other cases into the account. I’ll try to resolve this by myself and come back with my own solution and post it here!

Thank you very much for your reply. I have indeed another problem regarding other cases. I’ll try to take care of this problem myself and will post my solution later!

Huge thanks to both @camperextraordinaire @welshie123

Went in and checked out some of the methods I could use from MDN and found slice!

function titleCase(str) {
  str = str.toLowerCase();

  // Declare an array to store the passed and splited string argument
  var strSplit = [];
  strSplit = str.split(" ");

  // Declare an array where capitalized strings will be stored
  var strUpperCase = [];

  // Declare a number i for the loop function below
  var i = 0;

  // Loop function to iterate through the strSplit array and capitalize each entry
  while (i <= strSplit.length - 1) {
    strUpperCase.push(strSplit[i].charAt(0).toUpperCase() + strSplit[i].slice(1, strSplit[i].length));
    i++;
  }
    
  // Declare an array to join the capitalized strings
  var strJoin = strUpperCase.join(" ");
  return strJoin;
  
}