Title Case a Sentence - code seems to work but fails test cases

Title Case a Sentence - code seems to work but fails test cases


Hi! I’m working on the “Title Case a Sentence” challenge and have what I believe to be working code (see below). I can call titleCase() manually using the different test case strings and see that the function returns the expected results in the “console”, however when I run the tests, every test case fails, except for the first test case (function should return a string). After taking a look at the hints for this challenge, I see that there’s a more elegant way to do this (using array.prototype.map instead of iterating over array elements using a loop and using string.prototype.charAt() with string.prototype.replace() instead of converting to a character array and back to change the first character), but I’d like to know why the code below fails the test cases, because as best as I can tell it does in fact function the way it should. Any thoughts would be appreciated, thanks!

function titleCase(str) {
  // Split the string to get an array of strings containing 
  // each word of the sentence in all lower case letters.
  var splitStr = str.toLowerCase().split(" ");
  // Initialize the string that will be returned.  We'll concatenate 
  // each word to this string after the first letter is capitalized
  var retStr = "";
  // Iterate through the array of words and capitalize
  // the first letter in each one.
  for(var i=0; i < splitStr.length; i++){
    // Capitalize the first letter
    var charArr = splitStr[i].split("");
    charArr[0] = charArr[0].toUpperCase();
    // Concatenate to the return string
    retStr+= " " + charArr.join("");
  return retStr;

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36.

Link to the challenge:


I found my problem! A really dumb mistake! The way I concatenate the strings results in an extra space at the beginning of each sentence that you can’t easily see in the output on the FCC challenge page. When I split the string and look at it in my browser’s dev tools console it’s obvious.