How to capitalize the first character of each word in a string in Javascript

Josh Sherman
1 min read
Software Development JavaScript

The other day I had posted on capitalizing the first letter of a string in JavaScript. But what if you wanted to capitalize the first letter of every word? With PHP it’s just a simple call to ucwords and just as easy in Ruby and Python.

To be able to pull this off we will need to leverage the power of regular expressions to:

var lower = 'this is an entirely lowercase string';
var upper = lower.replace(/\w\S*/g, function (word) {
  return word.charAt(0).toUpperCase() + word.substr(1).toLowerCase();
});

There is a slight assumption that you want to force the rest of the string to be lowercased in the example. If you would prefer to retain the existing case, just omit the final .toLowerCase().

This can also be simplified quite a bit using modern syntax (golf much?):

lower.replace(/\w\S*/g, (w) => (w.replace(/^\w/, (c) => c.toUpperCase())));

If you’re okay with adding a new dependency to your project, you can also use my string lib called “Luthier” which has an upperCaseWords() method and many other string utilities. Check it out on GitHub

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles