Title Case a Sentence - working code, not accepted answer

Tell us what’s happening:
Hello. I have implemented the code according to instructions. When running, it is always correct. Could you help me why it is not accepted as an answer? I have also tested in locally.

Your code so far

function titleCase(str) {
  var lower = str.toLowerCase();
  var splitted = lower.split(" ");
  var cap, finalWord;
  var words = "";
  for (var i = 0; i < splitted.length; i++){
    cap = splitted[i].charAt(0).toUpperCase();
    finalWord = cap + splitted[i].substr(1);
    words += finalWord + " ";
  }
  str = words;
  return str;
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/title-case-a-sentence

The problem seems due to the space which is coming after the whole sentence which is causing the Test Cases to fail.

I'm A Little Tea Pot .

The space between last ‘t’ and ‘.’ seems to be the issue.


In the screencapture it seems correct.

Hello! I think the issue is in your for loop. You’re adding final word + " " repeatedly, so this puts a " " at the end of your final word, too.

You could shave off the last character of the sentence, but this might make your program a little too lengthy and harder than it needs to be. I recommend trying again, using the .join function!

You could use the trim method to get rid of the extra space on the end or change the following line:

words += finalWord + " ";

to

words += finalWord + (i === splitted.length - 1 ? "" : " ");

which uses the ternary operator to check if the variable i is equal to last index (to add a blank string) or another index (to add a space character).

Thank you very much. This was the piece of code that I was looking for.