How to Make First Letter of Each Word Capital in Javascript

In this tutorial, you will learn how to make first letter of each word capital in javascript. There are different case styles for a word such as upper case, lower case, camel case, etc. From a developer perspective, it can be a bit tricky to make the first letter of each word capital.

There are numerous ways to make the first letter of each word capital. But for the sake of simplicity, we will use toUpperCase() and toLowerCase() to capitalize or uncapitalize all letters in a word, but there is no built-in method in javascript to capitalize the first letter of a word.

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.
  • We have only included our javascript file script.js with a script tag at the bottom. The javascript code will run as soon as the page is loaded in the browser.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <script src="script.js"></script>
</body>
</html>

Javascript

  • 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 = 'make first letter of each word in capital';


function titleCase(msg){    
    return msg.split(' ').map(word =>  word.charAt(0).toUpperCase() + word.substr(1).toLowerCase()).join(' ');;
}

console.log(titleCase(myMsg));