Title Case a Sentence - Code correct, won't pass section

Title Case a Sentence - Code correct, won't pass section
0

#1

Can someone tell me why my code isn’t passing? I’ve tried it in C9 and all of the words are coming back with capitalized first letters. Even the console in FCC comes back correct. Here’s the code:


function titleCase(str) {
  var arr = str.toLowerCase().split(' ');
  str = "";
  
arr.forEach(function(word){
    var newArr = word.toString().split('');
    newArr[0] = newArr[0].toUpperCase();
    word = newArr.join('').toString();    
    str = str + " " + word;
  });     
  console.log(str);
  return str;
}

titleCase("I'm a little tea pot");
titleCase("sHoRt AnD sToUt");
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT");

*edit - here’s what comes back in the console in C9:

keggatron:~/workspace/tests $ node tests.js
 I'm A Little Tea Pot
 Short And Stout
 Here Is My Handle Here Is My Spout

#2

Your outputs have a leading space. Fortunately leading and trailing spaces are easy to remove. Just return str.trim() instead of just str.


#3

Instead of string concatenation, you could also try using map which gives you the opportunity to return a new array of modified data. Here’s your code modified to use the map function:

function titleCase(str) {
  var words = str.toLowerCase().split(' ');
  words =  words.map(function(word){
    var newArr = word.toString().split('');
    newArr[0] = newArr[0].toUpperCase();
    return newArr.join('').toString();    
  });     
  return words.join(' ');
}

Just for fun, here’s an even shorter example:

function titleCase(str) {
  var words = str.toLowerCase().split(' ');
  return words.map(function(word) {
    return word.slice(0,1).toUpperCase() + word.slice(1);
  }).join(' ');
}

#4

Thanks! That worked I was ripping my hair out about that.