確保字符串的每個(gè)單詞首字母都大寫,其余部分小寫。
像'the'和'of'這樣的連接符同理炫欺。
當(dāng)你完成不了挑戰(zhàn)的時(shí)候,記得開大招'Read-Search-Ask'熏兄。
這是一些對(duì)你有幫助的資源:
String.split()
Test:
titleCase("I'm a little tea pot") 應(yīng)該返回一個(gè)字符串
titleCase("I'm a little tea pot") 應(yīng)該返回 "I'm A Little Tea Pot".
titleCase("sHoRt AnD sToUt") 應(yīng)該返回 "Short And Stout".
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") 應(yīng)該返回 "Here Is My Handle Here Is My Spout".
//方法1:charAt() + slice();
function titleCase(str) {
var newStr = str.toLowerCase().split(" ");
for(var i=0;i<newStr.length;i++){
newStr[i] = newStr[i].charAt(0).toUpperCase() + newStr[i].slice(1);
}
return newStr.join(" ");
}
console.log(titleCase("I'm a little tea pot"));```
//方法2:map() + charAt() + slice()
function titleCase(str) {
return str.toLowerCase().split(" ").map(function(word){
return (word.charAt(0).toUpperCase() + word.slice(1));
}).join(" ");
}
console.log(titleCase("I'm a little tea pot "));```
//方法3:map() + replace()
function titleCase(str) {
return str.toLowerCase().split(" ").map(function(word){
return word.replace(word[0],word[0].toUpperCase());
}).join(" ");
}
console.log(titleCase("I'm a little tea pot"));```
//錯(cuò)錯(cuò)錯(cuò)
function titleCase(str) {
arr=str.toLowerCase().split(' ');
for(var i = 0;i<arr.length;i++){
var arr2=arr[i].replace(arr[i].charAt(0),arr[i].charAt(0).toUpperCase());
}
return arr2;
}
console.log(titleCase("I'm a little tea pot"));//Pot```