Help: Title Case a Sentence

Hello FCC -

I’m having trouble solving this challenge. My thought process was to first turn the string into all lower case letters, use split to turn it into an array and then iterate through the array and replace the first letter of each item with a capital letter.

My code works correctly for all items in the array until the last item is reached. In the output below, you see that the “t” in “LiTtle” is capitalized when instead, the “t” in “teapot” should be capitalized. I’m guessing my problem doesn’t run correctly when I replace the first letter of a word with a capital letter. Can someone point me in the right direction? Thanks in advance!

function titleCase(str){
   str = str.toLowerCase();
   var array = str.split(" "); 
   for(var i = 0; i < array.length; i++){
	  var firstLetter = array[i][0];
	  var capLetter = array[i][0].toUpperCase();
	  str = str.replace(firstLetter, capLetter);
   }
   return str;
}

titleCase("I'm a little tea pot");
 // output is "I'm A LiTtle Tea pot" but should be "I'm A Little Tea Pot"

Hi there, the problem is you are using replace to search for letters… so when you pull array[2][0] you are getting t, and then you are telling your string to replace t with T thats why your getting “LiTtle”

Try being more direct about which characters you want to replace.
(im trying to point you in the direction without give it to you, so I hope that helps :slight_smile: :confused:

  • Nao

Your algorithm and thought process is correct. But what is going wrong:

str = str.replace(firstLetter, capLetter);

When using the .replace() method with a value (Not a regular expression), only the first instance of the value will be replaced. This why your returned string is incorrect.

You have 3 "t"s and only the first one is replaced by your method.
I have used the .match() method to track how .replace() is manipulating your string:

####Screenshot of the console log:

Logs used inside the for loop:

  console.log("Letter To UpperCase: '" + array[i][0] + "' - Result of Match:");
  console.log(str.match(firstLetter));
  console.log("\n");

I would recommend using .splice() instead of .replace(). However, if you insist solving this challenge using the .replace() method, it would be beneficial to look into regular expressions.


Tip: Splice and Replace are one of the many methods to handle/solve this problem.
Goodluck.