There are numerous ways to make the first letter of each word capital. But for the sake of simplicity, we will use
In the following example, we have one global variable that holds a string. We will make the first letter of each word capital and display the result on the screen. 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.
script.js with a
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
- 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
- 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
- We are joining the first capitalized letter and rest of the lowercase letters by using the addition (
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
const myMsg = 'make first letter of each word in capital';
return msg.split(' ').map(word => word.charAt(0).toUpperCase() + word.substr(1).toLowerCase()).join(' ');;