FreeCodeCamp:Title Case a Sentence
要求:
确保字符串的每个单词首字母都大写,其余部分小写。
像'the'和'of'这样的连接符同理。
结果:
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 function titleCase(str){
2 var arr=str.split(" ");
3 var newArray=[];
4 for (var i=0;i<arr.length;i++){
5 var newStr=arr[i].slice(0,1).toUpperCase()+arr[i].slice(1).toLowerCase();
6 newArray.push(newStr);
7 }
8 return newArray.join(" ");
9 }
10
11 titleCase("I'm a little tea pot");