2
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.

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97
Selvidian
  • 45
  • 7

2 Answers2

5

There are 3 issues in your code,

  • Your for loop is wrong, it should be i < one.length
  • You're not splitting the words but the entire string.
  • You have to put back the space between the words.

    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"));
J0B
  • 1,648
  • 1
  • 12
  • 24
Musa
  • 96,336
  • 17
  • 118
  • 137
1

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

Dimitris Karagiannis
  • 8,942
  • 8
  • 38
  • 63