How to Capitalize First Letter of Each Word in JavaScript?

In this article, you will learn how you can capitalize the first letter of each word using JavaScript.

You are given a string of length n which contains space-separated words. Your task is to convert the first letter of each word to uppercase.

For example:

Input   -> 'hello my name is john doe'
Output  -> 'Hello My Name Is John Doe'

You can achieve this in the following 3 steps:

  • Step 1 – Split the string at each occurrence of space(' ') using the string.split() method. This will result in an array containing each word of the string.
  • Step 2 – Loop through the words array and convert the first character of each word to uppercase using the toUpperCase() method.
  • Step 3 – Join each word of the above array with a space(' ') using the Array.join() method. This will again convert the words array into a string containing space-separated words.

Here is the implementation of the above three steps using JavaScript:

function capitalize(words){
    
    // Split the string at each occurrence of a space
    let wordsArr = words.split(' ');
    
    // Loop through each word
    for(let i=0;i<wordsArr.length;i++){
        
        // Convert the first letter to uppercase
        wordsArr[i] = wordsArr[i][0].toUpperCase() + wordsArr[i].substring(1);
    }
    
    // Join the words with a space character
    // and return the result
    return wordsArr.join(' ');
}

let words = 'hello my name is john doe';
let result = capitalize(words);

// Print the result
console.log(result);

Output:

Hello My Name Is John Doe

Solution 2:

You can even make the above solution much simpler and shorter using the map() function.

Here is a shorter version of the above solution:

let words = 'hello my name is john doe';
let result = words
            .split(' ')
            .map(word=> word[0].toUpperCase()+word.substring(1))
            .join(' ');
            
console.log(result);

Output:

Hello My Name Is John Doe

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts