将字符串中的每个单词的首字母大写 – JavaScript
作者:互联网
这个功能有什么问题?我失去了感谢你的帮助.
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
if (splitStr.length[i] < splitStr.length) {
splitStr[i].charAt(0).toUpperCase();
}
str = splitStr.join(' ');
}
return str;
}
titleCase("I'm a little tea pot");
解决方法:
您没有再次将更改分配给阵列,因此您的所有努力都是徒劳的.试试这个:
function titleCase(str) {
var splitStr = str.toLowerCase().split(' ');
for (var i = 0; i < splitStr.length; i++) {
// You do not need to check if i is larger than splitStr length, as your for does that for you
// Assign it back to the array
splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);
}
// Directly return the joined string
return splitStr.join(' ');
}
document.write(titleCase("I'm a little tea pot"));
标签:javascript,string,capitalize,charat 来源: https://codeday.me/bug/20190918/1810759.html