确保字符串的每个单词首字母都大写,其余部分小写
titleCase("I'm a little tea pot") should return a string.
titleCase("I'm a little tea pot") should return "I'm A Little Tea Pot".
titleCase("sHoRt AnD sToUt") should return "Short And Stout".
titleCase("HERE IS MY HANDLE HERE IS MY SPOUT") should return "Here Is My Handle Here Is My Spout".
//方法一:charAt() + slice
function titleCase(str) {
var arr = str.toLowerCase().split(" ");
for(var i=0;i<arr.length;i++){
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join(" ");
}
titleCase("I'm a little tea pot");```
//方法二:charAt() + replace
function titleCase(str) {
var arr = str.toLowerCase().split(" ");
var result = arr.map(function(val){
return val.replace(val.charAt(0),val.charAt(0).toUpperCase());
});
return result.join(" ");
}
titleCase("I'm a little tea pot");
https://github.com/freeCodeCamp/freeCodeCamp/wiki/Algorithm-Title-Case-A-Sentence
网友评论