Title case a sentence. Why is my code not accepted?

I solved the challenge in VS code, and it looks like it is working there. But when I come over to paste it in the challenge page her, it trows many errors. I seem to be unable to understand what is wrong with my code.
Can anybody out there help me?
this is my code so far:

function titleCase(str) {
let words = str.toLowerCase().split(’ ');
let newString = ‘’;
for (let i = 0; i < words.length; i++) {
let first = words[i][0].toUpperCase();
let last = words[i].substring(1);
let wordsCapital = first + last;
newString = newString + ’ ’ + wordsCapital;;
}
console.log(newString);
return newString;
}

titleCase(“HERE IS MY HANDLE HERE IS MY SPOUT”);


function titleCase(str) {
return str;
}

titleCase("I'm a little tea pot");
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36.

Challenge: Title Case a Sentence

Link to the challenge:

Based on your current logic, you are adding an extra space character to the beginning of the string. Instead of returning a string like "I'm A Little Tea Pot", you are returning " I'm A Little Tea Pot"

1 Like

Yes, this is correct. It is because at the end of the loop I am defining newString = newString + …, and the newString at this moment is an empty string.
Thank you Randell. I will look for a workaround :slight_smile:

I solved it by adding newString = newString.trim() out of the loop just before the return statement.
Thanks again, I appreciate your help

why not loop thruogh the string and look if the character behind your current character is a space, if it is add an uppercase. if the character behind is not a space, add the character lower case.
easy, simple and very quick (exactly O(n) iterations when n is the length of the string)

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