We can use the string toUpperCase and substring methods to convert each word in a string to have their first letter in uppercase.
For instance, we can write:
const titleCase = (str) => {
const splitStr = str.toLowerCase().split(' ');
for (const [i, str] of splitStr.entries()) {
splitStr[i] = str[0].toUpperCase() + str.substring(1);
}
return splitStr.join(' ');
}
console.log(titleCase("I'm a little tea pot"));
We create the titleCase function with the str string parameter.
We split the string by the space character with the split method.
Then we loop through each string in the split string array with the for-of loop.
We get the index i and string str from each entry by destructuring the entries returned by entries .
After that, we get the first character of str and convert that to uppercase. Then we concatenate that with the rest of the str string that we get from substring .
Finally, we join the string back together with a space character in between each word with join .
Therefore, the console log should log 'I’m A Little Tea Pot’ .