How do I capitalize the first letter of each word in a string in JavaScript?
Davide S
davide s profile pic

To capitalize the first letter of each word in a string in JavaScript, you can use various techniques such as string manipulation and regular expressions. Here's a step-by-step guide on how to achieve this: 1. Get the string you want to capitalize:

1
2
3

   const sentence = 'the quick brown fox';
   

Replace'the quick brown fox' with the actual string you want to capitalize. 2. Capitalize the first letter of each word using string manipulation: - Split the sentence into an array of words:

1
2
3

     const words = sentence.split(' ');
     

- Iterate over the words and capitalize the first letter of each word:

1
2
3

     const capitalizedWords = words.map(word => word.charAt(0).toUpperCase() + word.slice(1));
     

In this example, themap() method is used to iterate over each word in thewords array. For each word, the first letter is capitalized usingword.charAt(0).toUpperCase(), and the rest of the word is added usingword.slice(1). The result is an array of capitalized words. - Join the capitalized words back into a string:

1
2
3

     const capitalizedSentence = capitalizedWords.join(' ');
     

This step joins the capitalized words using a space character, resulting in the final capitalized sentence. 3. Use the capitalized sentence: Once the sentence is capitalized, you can use it as needed.

1
2
3

   console.log(capitalizedSentence);
   

This example logs the capitalized sentence to the console. By following these steps, you can capitalize the first letter of each word in a string in JavaScript. Ensure that you handle any specific requirements or edge cases related to your string, such as multiple spaces between words or special characters.