Ahsan Alii Ahsan Alii - 3 years ago 136
Javascript Question

Capitalize the first letter of each string

I've been trying to capitalize the first letter of each word in a string, but it says

TypeError: Cannot assign to read only property '0' of string 'i'
. My logic looks fine but surely the way I'm doing this is not right. Any suggestions.



function titleCase(str) {
str = str.toLowerCase();
var word = str.split(" ");
// console.log(word[0][0]);
for (var i = 0; i < word.length - 1; i++) {
word[i][0] = word[i][0].toUpperCase();
}
console.log(word);
return word;
}

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




Answer Source

Try like so: (see comments in code)

function titleCase(str) {
  str=str.toLowerCase();
  var word = str.split(" ");
  for (var i=0; i < word.length; i++) {  // you don't neet -1 here as you had
    word[i] = word[i].charAt(0).toUpperCase() + word[i].slice(1); // see changes in this line
  }
  console.log(word);
  return word;
}

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download