Reputation: 45
function titleCase(str) {
var one = str.split('');
for(var i = 0;i>one.length;i++) {
one[i] = one[i].charAt(0).toUpperCase() + one[i].slice(1);
}
var final = one.join("");
return final;
}
titleCase("I'm a little tea pot"); // yields "I'm a little tea pot", unchanged
Can you explain to me why it doesn't work? I'm supposed to capitalize first letters of every word in this string.
Upvotes: 2
Views: 54
Reputation: 97727
There are 3 issues in your code,
i < one.length
function titleCase(str) {
var one = str.split(' ');
for(var i = 0;i<one.length;i++) {
one[i] = one[i].charAt(0).toUpperCase() + one[i].slice(1);
}
var final = one.join(" ");
return final;
}
alert(titleCase("I'm a little tea pot"));
Upvotes: 5
Reputation: 9386
You have the following logical errors:
1) You are splitting the sting on every single letter instead of every word. Use. split(' ')
instead of .split('')
2) You are checking for i > one.length
which is never the case since i
starts as 0
. You should do i < one.length
Upvotes: 1