Please help withTitle Case a Sentence

Tell us what’s happening:
why is my algorithm not working ?

Your code so far


function titleCase(str) {
 var splited = str.split(" ");
 var changed = "";
 for(let i=0; i < splited.length; i++) {
   splited[i][0].toUpperCase();
    
 }
return splited;
}

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



Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence

The above refers to each word in splited as you iterate through.

splited[i][0]

The above refers to the first letter of each word as you iterate through.

splited[i][0].toUpperCase();

The above returns the first letter of each word as a capitalized version as you iterate through.

The problem with the last line above is that toUpperCase returns a value and does not changed the original value. It returns a new string.

Basically, you are never changing any of the words in splited. You need to “build” the new version of the word using what you have above concatenated with the remaining part of each word (after the first character) and reassign back to splited[i] in each iteration. Finally, the final result should be a string and not an array (which splited is), so you will need to convert it back to a string.

1 Like

thank you. am still battling with how i can “build” version of word using my existing code concatenated…

Again, you already know how to create the capitalized first letter. You could use splice or substring to get the rest of the word. Then, just concatenate those two parts.

my code is returning the correct output but for some reason it is not passing. This is my new code

function titleCase(str) {
 var splited = str.split(" ");
 var changed = "";
 for(let i=0; i < splited.length; i++) {
  changed += splited[i][0].toUpperCase() + splited[i].toLowerCase().substr(1) + " ";
  var strind = changed.toString();
    
 }
return strind;
}

var result = titleCase("HERE IS MY HANDLE HERE IS MY SPOUT");
console.log(result);



Your browser information:

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

You might have an extra space at the end of the string.