Sling Academy
Home/JavaScript/JavaScript: How to Capitalize all Words in a String

JavaScript: How to Capitalize all Words in a String

Last updated: February 22, 2023

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!

Next Article: JavaScript Regular Expressions: Extract & Validate URLs

Previous Article: JavaScript: 3 Ways to Create Multiline Strings

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration