JavaScript: How to Capitalize all Words in a String

Updated: February 22, 2023 By: Khue Post a comment

Capitalizing all words in a string can be useful in situations where you want to standardize the formatting of text, such as when displaying titles or headings. This concise, example-based article will show you how to do that in JavaScript.

What is the point?

To capitalize all words in a given string, we can use the split() and map() methods to split the string into an array of words and then apply the toUpperCase() method to the first letter of each word.

Example:

const capitalizeWords = (str) => {
  // Split the string into an array of words
  const wordsArray = str.split(' ');

  // Map over the array and capitalize the first letter of each word
  const capitalizedWordsArray = wordsArray.map(
    (word) => word.charAt(0).toUpperCase() + word.slice(1)
  );

  // Join the capitalized words back into a string
  const capitalizedString = capitalizedWordsArray.join(' ');

  return capitalizedString;
};

// Example usage
console.log(capitalizeWords('hello world!'));
console.log(capitalizeWords('goodbye world!'));
console.log(capitalizeWords('welcome to sling academy, where you can learn to code!'));

Output:

Hello World!
Goodbye World!
Welcome To Sling Academy, Where You Can Learn To Code!

That’s it. Happy coding and have a nice day!