How to Capitalize Words in JavaScript

How to Capitalize Words in JavaScript

Ferenc Almasi β€’ 2020 October 13 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

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

Copied to clipboard!
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

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:

Copied to clipboard! Playground
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

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

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.