I'm struggling to capitalize the first letter of each word in a string. Specifically, my function converts "I'm a little tea pot" to "i'm a little tea pot" instead of the desired output, "I'm A Little Tea Pot." Here's my JavaScript code:
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"));
The error in your code lies in not assigning the modified word back to the array correctly. To resolve this issue, modify your code as follows:
function titleCase(str) { var splitStr = str.toLowerCase().split(' '); for (var i = 0; i < splitStr.length; i++) { // No need to check if i is larger than splitStr length, as your for loop does that for you // Assign it back to the array splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1); } // Return the joined string directly return splitStr.join(' '); } document.write(titleCase("I'm a little tea pot"));
Changes made:
The above is the detailed content of How to Capitalize the First Letter of Each Word in a String in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!