joshtronic

in Software Development #JavaScript

How to capitalize the first character of each word in a string in 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