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 thestring.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 theArray.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