Title Case a Sentence confusion

Title Case a Sentence confusion
0

#1

Hi everyone!

So I’m trying to solve the Title Case a Sentence problem and I’ve written some code for it, but it’s not outputting a joined string and I’m not sure why.

Here’s my code:

function titleCase(str) {
  var stringArray = str.toLowerCase().split(" ");
  for (var i = 0; i < stringArray.length; i++) {
   return stringArray[i].charAt(0).toUpperCase() + stringArray[i].slice(1);
  }
  return stringArray.join();
}

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

Thank you for your help!


#2

Your for loop only makes one iteration before you return the first word as a capitalized word. Once the function executes the return statement, the function is exited regardless if the for loop has finished iterating.

  for (var i = 0; i < stringArray.length; i++) {
   return stringArray[i].charAt(0).toUpperCase() + stringArray[i].slice(1);
  }

Also, you might want to specify a delimiter for your join function. Since you did not provide one, it will join each element in the array with a comma.


#3

Thanks so much for your help! I changed my code, but now I get an error message that my .join() method is not a function / undefined. I don’t know how it’s undefined.

function titleCase(str) {
  var stringArray = str.toLowerCase().split(" ");
  for (var i = 0; i < stringArray.length; i++) {
   str = stringArray[i].charAt(0).toUpperCase() + stringArray[i].slice(1);
  }
  return str.join(" ");
}

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

#4

join can only be used on arrays. str is a string containing only the last word. Try building an array out of the words. You can use push to do so. Then, at the end you can return a joined array of words. Also, you do not have to split str into an array. You can reference a strings characters by their index the same way you do with an array. For example, I could reference the 2 character of the original string passed into the function with:

var secondCharOfStr = str[1];