How to Capitalize Words in JavaScript

How to Capitalize Words in JavaScript

Ferenc Almasi β€’ 2020 October 13 β€’ πŸ“– 1 min read

If you want to capitalize words in JavaScript, you can use the following function which makes use of replace, toUpperCase and some regex:

const capitalize = str => str.replace(/\b\w/g, substr => substr.toUpperCase());

// This will return: "Lorem Ipsum Dolor Sit Amet..."
capitalize('lorem ipsum dolor sit amet...');
capitalize.js
Copied to clipboard!

The regex for the string replace uses an anchor and a word boundary to match the first character of every word. If you need to capitalize only the very first letter of your string, you can use the following solution:

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();

// This will return: "Lorem ipsum dolor sit amet..."
capitalize('lorem ipsum dolor sit amet...');

// This also works for wrong capitalizations:
capitalize('lOREM IPsUm dolor sit amet...');
capitalize.js
Copied to clipboard!

This function will get the first character of your string (charAt(0)), turn it into uppercased, and then slice(1) returns the rest of the string, lowercased.

How to Capitalize Words in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended