Title Case a Sentence -- Freecodecamp

确保字符串的每个单词首字母都大写,其余部分小写。
像'the'和'of'这样的连接符同理。
当你完成不了挑战的时候,记得开大招'Read-Search-Ask'。
这是一些对你有帮助的资源:
String.split()
Test:
titleCase("I'm a little tea pot") 应该返回一个字符串
titleCase("I'm a little tea pot") 应该返回 "I'm A Little Tea Pot".
titleCase("sHoRt AnD sToUt") 应该返回 "Short And Stout".
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") 应该返回 "Here Is My Handle Here Is My Spout".

//方法1:charAt() + slice();
function titleCase(str) {
var newStr = str.toLowerCase().split(" ");
for(var i=0;i

//方法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"));```

//错错错
function titleCase(str) {
arr=str.toLowerCase().split(' ');
for(var i = 0;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```

Copy from https://medium.freecodecamp.com/three-ways-to-title-case-a-sentence-in-javascript-676a9175eb27#.s74dahc0m

你可能感兴趣的:(Title Case a Sentence -- Freecodecamp)