To accomplish our goal, we will create a custom method that will take a string as a parameter. It will capitalize the first letter of each word in that string and return it.
In the following example, we have one global string. We will capitalize the first letter of each word and log the final string in the console window. Please have a look over the code example and the steps given below.
HTML & CSS
We do not have any element in the HTML file because it is not required for this tutorial.
We have a global variable myMsg and it holds a string.
We have created a custom method titleCase() which takes a string as a parameter.
Inside the titleCase() method, we are splitting the string using the split() method. We are doing so to get rid of spaces in the string. This method will return an array of words.
We are using the map() method to iterate over each word. Inside this method, we are using the charAt() method and passing 0 as a parameter to get the first letter in the word. We are capitalizing the first letter by calling the toUpperCase() method.
We are using substr() and passing 1 as a parameter to get all the letters in the word except the first one. We are changing their case to lower by calling the toLowerCase() method.
We are joining the first capitalized letter and rest of the lowercase letters by using the addition (+) operator.
The map() method returns an array, but we are expecting a string. That is why we are calling the join() method and passing a space as a parameter. This will result in a space between each word.
We are calling the titleCase() method and passing string myMsg as a parameter. We are logging the string returned by this method in the console window by using the console.log() method.
const myMsg = 'This is my string and please Capitalize first letter of every word in it';
return msg.split(' ').map(word => word.charAt(0).toUpperCase() + word.substr(1).toLowerCase()).join(' ');;