Selvidian
Selvidian

Reputation: 45

Why my capitalization of javascript string is not working

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

Answers (2)

Musa
Musa

Reputation: 97727

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"));

Upvotes: 5

Dimitris Karagiannis
Dimitris Karagiannis

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

Related Questions