Explain Codes LogoExplain Codes Logo

How can I capitalize the first letter of each word in a string using JavaScript?

javascript
functions
regex
best-practices
Alex KataevbyAlex Kataev·Aug 29, 2024
TLDR

Quick way to capitalize: using String.prototype.replace() with /\b\w/g regex targeting word beginnings, and .toUpperCase() for conversion.

Example:

const capitalize = s => s.replace(/\b\w/g, c => c.toUpperCase()); // Who needs lower case anyway?

Usage:

console.log(capitalize('quick brown fox')); // Expect: 'Quick Brown Fox', Actual: 'Quick Brown Fox'.Coincidence? I think not!

A step-by-step approach

Understanding the regex magic

Here, /\b\w/g is our regex pattern used in the fast answer. It matches the first letter of each word. In the pattern, \b is a word boundary, \w matches any word character, and g applies a global search.

Using ES6 features for more conciseness

Consider an advanced yet clean implementation of it using the power of ES6.

const capitalizeWords = str => str.toLowerCase().split(' ').map(word => word.charAt(0).toUpperCase() + word.substring(1)).join(' '); // Don't break the chain!

Mistakes developers often make

Crucial to note, always actively assign the changes back to the array when modifying it, as functions like map yield a new array.

Beyond capitalization and JavaScript

When CSS can save your day

There are moments when using text-transform: capitalize; in CSS makes more sense. It's pure visual formatting, while the actual data remains unchanged.

The power of JavaScript for dynamic updates

In scenarios with interactivity or dynamic updates, JavaScript is your superhero here. CSS doesn't stand a chance.

Mastering advanced techniques

Usage of array methods

We have JavaScript's map() function for us. Here's how to employ it with arrow functions:

const capitalizeWords = str => str .toLowerCase() .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' '); // Mapping the world, one word at a time!

Regex to the rescue

Regex fans will fall in love with the power and brevity of replace() in this one-liner:

const capitalizeWords = str => str.replace(/(?:^|\s)\S/g, a => a.toUpperCase()); // Regex, Assemble!

Don't forget to test

Always test your function with different strings. Look out for special characters or mix cases. Real-world data is rarely perfect!

Balancing readability and complexity

While fancier solutions can be alluring, readability and maintainability should be prioritized.