Title Case a Sentence - something's off

The console shows the letters being the way the exercise wants, but it’s incorrect.

 let x = str.split(' ')  
  let y
for(let i = 0; i < x.length; i++) {
  y = x[i][0].toUpperCase() + x[i].substring(1).toLowerCase()
    console.log(y)
  };
  
return y  
}

You aren’t logging what you think you are logging:

function titleCase(str) {
  const splitStr = str.split(' ');
  let outputStr;
  for (let i = 0; i < splitStr.length; i++) {
    outputStr = splitStr[i][0].toUpperCase() + splitStr[i].substring(1).toLowerCase();
  }

  return outputStr
}

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

I’m almost there, it seems, with this code.

const splitStr = str.split(' ');
  let outputStr = '';
  for (let i = 0; i < splitStr.length; i++) {
  outputStr += splitStr[i][0].toUpperCase() + splitStr[i].substring(1).toLowerCase()
    
  };
return outputStr;
};

This is what the console is showing:

I'mALittleTeaPot

Can anyone give me a hint (not the answer). Thanks!!

It looks like the words don’t have spaces between them, right?

So, where do I create the space…

It needs to happen it between the places where you stick two words together, right? Where are you doing that?

Okay, so I did the following:

  const splitStr = str.split(' ');
  let outputStr = '';
  for (let i = 0; i < splitStr.length; i++) {
  outputStr +=` ${splitStr[i][0].toUpperCase()}${splitStr[i].substring(1).toLowerCase()}`
}

And the console is showing:

I'm A Little Tea Pot

But it’s still not good. Maybe extra spaces.

Yup. You are close. You have one space too many.

So, the only way, as of now, that I’ve been able to create those spaces is by there being a space between a backtick and a curly bracket but still not good…

What’s happening right now is that you are putting an extra space at the beginning of the string. Do you want a space before the first word?

I used this regex, and I cannot see the space anymore, but still…

let newString = outputStr.replace(/\s/,' ').trim();

Got it. Thanks for the help.

1 Like

That is a bit more code than is actually needed.

You could simply return outputStr.trim() or return outputStr.slice(1). Either of these would remove the extra space character on the far left of outputStr created in the first iteration of the for loop’s Template Literal.

Hmm, I see. It was the first time I used the trim method. Just looked it up on MDN. Thanks.