字符串中,每个单词由空格隔开,空格的个数不限
function capitalize(sting) {
var words = string.split(" ");
for(var i = 0; i words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
}
return words.join(" ");
}
var string = "ajax cookie event object";
capitalize(string); // "Ajax Cookie Event Object"
注意代码中关键的一句
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
words[i].charAt(0).toUpperCase()只是取得字符串首字母,然后转换为大写字母,它并不会改变原字符串,所以需要和原字符串中的其他字符连接起来,并将新值赋给原字符串