Doubt about Title Case a Sentence

Hello everyone! I have a little doubt about this challenge, I don’t why my solution don’t pass the test. I print in the console the string returned and it is exactly the same as the examples it is showed in the test section with all the sentences.
Sorry by my English, it is not my language native.

function titleCase(str) {
let words = str.split(' ');
let aux;
let stringUpperCamel = "";
for(let i = 0; i < words.length; i++){
  aux = words[i][0].toUpperCase();
  for(let j = 1; j < words[i].length;j++){
    aux += words[i][j].toLowerCase();
  stringUpperCamel += aux;
  stringUpperCamel += ' ';
return stringUpperCamel;

console.log(titleCase("sHoRt AnD sToUt"));
  **Your browser information:**

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

Challenge: Title Case a Sentence

Link to the challenge:

Notice there’s one additional space at the end of the string. Changing console.log call to the following will make it visible:

console.log('"' + titleCase("sHoRt AnD sToUt") + '"');
1 Like

The extra space is what is causing it to fail and a naive way of fixing this is simply to cut it off at the end by using something like slice and in case you are not familiar: String.prototype.slice() - JavaScript | MDN

I took another quick look and you can simply add a conditional so that this line
stringUpperCamel += ' '; does not get ran on the last word and you will be fine, and I think that is a much better way to go about it than what I first recommended.

It is correct that the current issue is the whitespace at the end of your returned string.
You are currently storing the return object as a string and adding each word with the proper casing.
Have you considered storing all words in an array instead, and before returning the array, you use the array method .join()? This would enable you to specify how the strings in the array should be combined - in this case with a whitespace character - and it would leave no preceding or succeeding whitespace in your returned string.

See W3Schools .join() reference for more information including the syntax!

Thank you so much for all the replies! Now, I just fixed the problem adding a conditional for avoid return the string with the whitespace at the end :).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.