My answer is not being accepted. What's wrong in this code?

Tell us what’s happening:

Your code so far


function titleCase(str) {
let splitting = str.split(" ");
let collection = "";

splitting.forEach((element) => {
  collection +=
    element.slice(0, 1).toUpperCase() +
    element.slice(1).toLowerCase() +
    " ";
  return collection;
  });

console.log(collection);

return collection;
}

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

Your browser information:

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

Challenge: Title Case a Sentence

Link to the challenge:

The last space string you’re adding at the end of the chain on every iteration is the culprit. Since your output ends up like this "I'm A Little Tea Pot ", instead of "I'm A Little Tea Pot". It would be alright if It wasn’t because of the “space” character added at the end of the last string.

I suggest to initialize collection as an empty array, then push the Capitapized string in collection on every iteration. Then afterwards, use collection.join(’ ') to transform the array into a string and then return the result. You can also remove the trailing space with slice after the cycle, feel free to do and come up with whatever other solution.

2 Likes

As said, you have an extra space at the end of the string. One option might be just to trim the string before returning it.

Also, you can’t return inside the forEach (you can just remove the line and keep the return at the end of the function).

2 Likes

@skarkantropo Thanks a lot!

@lasjorg Thanks a lot!