Learning JS (Title Case Sentence)

I’m trying to solve this problem with all the things I’ve learned so far, but my code is not working and the ways people are solving it is indeed very different.

My question here really is, why isn’t the following code doing the trick?
Just trying to understand the logic…


function titleCase(str) {
  var newArray = str.toLowerCase().split(" ");
  
 
  //Going through the array//
  for (var i = 0; i < newArray.length; i++){
    for (var j = 0; j < newArray[i].length; j++){

    //if index is in index 0 (letter) of the word//
    if (newArray[i][j] == newArray[i][0]){

      //change letter to uppercase//
      newArray[i][j].toUpperCase();
      }

    }
  }
  return newArray;
 
  
}

titleCase("i'm a little tea pot");

Hey, congrats on your pursuit of JS! It will yield great dividends for your future.
I like the moderator’s comments on your code he is very helpful.
I would encourage you to look at using map(),split(),join(), toLowerCase() and toUpperCase().
These methods could help clean up your code and save a lot of typing which is always a good thing.:grinning: Hope this helps.
Happy Coding!

These links might be useful.
https://www.w3schools.com/jsref/jsref_join.asp
https://www.w3schools.com/jsref/jsref_obj_string.asp
https://www.w3schools.com/jsref/jsref_map.asp
https://www.w3schools.com/jsref/jsref_charat.asp
https://www.w3schools.com/jsref/jsref_split.asp

1 Like

Here is my solution:

function titleCase(str) {
  let x = str.split(' ');
  for (let i = 0; i < x.length; i++){
    if (x[i].length > 1) {
      let firstLetterUpper = x[i].charAt(0).toUpperCase()
      let wordWithoutFirst = x[i].substring(1, x[i].length)
      x[i] = firstLetterUpper + wordWithoutFirst.toLowerCase()
    }
    else x[i] = x[i].charAt(0).toUpperCase()
  }
  return x.join(' ')
}

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