Title Case a Sentence Returning Correct String but not passing challenge

Tell us what’s happening:
When I run console.log(titleCase("hello WORld"));, it logs out Hello World, but I’m not passing any of the four tests except for the first one. Is it because I’m returning newStr instead of str?

Your code so far

function titleCase(str) {
  // Make an array of subarrays containing the characters of each word of str
  let strArr = str.split(' ').map(v => v.split(''));
  // Initialize a new string to output
  let newStr = "";
// Make the first letter of every subarray capital and the rest lowercase
  strArr = strArr.map(v => v.map((v, i) => i === 0 ? v.toUpperCase() : v.toLowerCase()));
// Push the letters of each subarray to the console followed by a space
  strArr.forEach(v => {
    v.forEach(v => {
      newStr += v;
    newStr += " " ;
  // Return the new string
  return newStr;
console.log(titleCase("hello WORld"));

Your browser information:

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

Link to the challenge:

Hey @fifn2,
This is what your function returns:

"Hello World "

This is what it should return:

"Hello World"

Can you spot the difference?
And then try solving.
Hope this helps.

1 Like

Oh my gosh thank you! I never would’ve caught that.

if (i < strArr.length - 1) {
      newStr += " ";

Just for the purpose of debugging, I know that when I debugged and used console.log(titleCase("hello world") === "Hello World") and it returned false that something was up. Is there a function that can output the difference between two strings that would catch that I had a space on the end?
console.log(differenceBetween(titleCase("hello world"), "Hello World"))
If something like that existed I would’ve caught it immediately.

You can use

console.log("->" + string + "<-")

Or whatever you like, but in this way you can see the beginning and end of a string