句中单词首字母大写
请将传入的字符串中,每个单词的第一个字母变成大写并返回。 注意除首字母外,其余的字符都应是小写的。在这个挑战中,我们还需要将诸如 the 和 of 之类的连接词大写
1 function titleCase(str) { 2 let shouldCap = true; 3 let res=''; 4 for(let i = 0; i<str.length; i++){ 5 if(shouldCap) { 6 res += str[i].toUpperCase(); 7 shouldCap = false; 8 } else { 9 res += str[i].toLowerCase(); 10 if(str[i]===' '){ 11 shouldCap = true; 12 } 13 } 14 } 15 return res; 16 } 17 titleCase("I'm a little tea pot");
toUpperCase()方法将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)toLowerCase()会将调用该方法的字符串值转为小写形式,并返回
1 function titleCase(str) { 2 return str.split(' ').map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()).join(' '); 3 } 4 titleCase("I'm a little tea pot");
1 function titleCase(str) { 2 return str.toLowerCase().replace( /(^|\s)[a-zA-Z]/g, match => match.toUpperCase()); //此处的match是参数 3 } 4 titleCase("I'm a little tea pot");
- title case: Tea Pot
- camel case: teaPot
- kekab-case: tea-pot
- snake case: tea_pot

浙公网安备 33010602011771号