TitleCase sentence

TitleCase sentence
0

#1

Tell us what’s happening:
Hello Everyone,
looks like i’m completely suck on this algorithm. I was able to split it to an array and changed everything to lowercase but i’m completely suck at this point. I did a loop but it only returns the first letter of the first word as upper case. Any help will be much appreciated.

Thanks,

Ray

Your code so far

function titleCase(str) {
 var array = str.toLowerCase().split(" ");
  var upperCase = [];
  for (var i=0;i<array.length; i++){
    upperCase = array[i][0].toUpperCase();
    return upperCase;
  }
  
}

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

Your browser information:

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

Link to the challenge:


#2

Your for loop iteration gets interrupted during the first iteration, because you put the return statement inside the for loop. You assigned the first letter (I) of the first word (I’m) to the upperCase variable and then you returned it. Once a return statement is executed, the function is immediately exited and nothing else happens.


#3

I am now able to get the first letter of each word into an array called upperCase. What is the best way to add these back to the original array?

function titleCase(str) {
var array = str.toLowerCase().split(" ");
var upperCase = [];
for (var i=0;i<array.length; i++){
upperCase.push(array[i][0].toUpperCase());
}
return upperCase;
}

titleCase(“I’m a little tea pot”);


#4

Why do you think you need to add them back to the original array? You created an array called upperCase via the for loop which contains the upper-case version of each word’s first letter. Since you already know how to get the upper-case of the first letter, why not concatenate it with the remainder of each word. You could use slice, substr, or substring function to do that. Then, you can take this concatenation and push the capitalized word into a new array and use the join function to put the string back together before returning it?


#5

I got it working! thank you so much for pointing me in the right direction. Below is the final answer.

function titleCase(str) {
var array = str.toLowerCase().split(" “);
var upperCase = [];
for (var i=0;i<array.length; i++){
upperCase.push((array[i][0].toUpperCase()) + (array[i].slice(1)));
}
return upperCase.join(” ");
}

titleCase(“I’m a little tea pot”);