字串中,每個單字由空格隔開,空格的個數不限
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()只是取得字串首字母,然後轉換為大寫字母,它並不會改變原始字串,所以需要和原字串中的其他字元連接起來,並將新值賦給原字串