slurrr slurrr - 1 month ago 11
Javascript Question

Capitalize First Letter of each word in a String - JavaScript

What is wrong with this function? I am lost thanks for help.

function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(' ');
}
return str;
}

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

Answer

You are not assigning your changes to the array again, so all your changes are in vein. Try this:

function titleCase(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

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