我正在尝试编写一个函数,将字符串中每个单词的首字母大写(将字符串转换为标题大小写)。
例如,当输入是 时"I'm a little tea pot",我希望"I'm A Little Tea Pot"是输出。但是,该函数返回"i'm a little tea pot".
"I'm a little tea pot"
"I'm A Little Tea Pot"
"i'm a little tea pot"
这是我的代码:
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; } console.log(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"));