Explain Codes LogoExplain Codes Logo

How to capitalize the first letter of each word, like a 2-word city?

javascript
string-manipulation
es6-features
performance-optimization
Nikita BarsukovbyNikita Barsukov·Jan 18, 2025
TLDR

Use .replace(/\b\w/g, c => c.toUpperCase()) to capitalize each word in a string:

const city = "san francisco"; // 'cause in JavaScript we have no fear to replace things const capitalized = city.replace(/\b\w/g, c => c.toUpperCase()); // "San Francisco"

Breaking down the fast answer

Prior transformation for smooth operation

To avoid the roller coaster ride of random capitalization, first convert your string to lower case:

const city = "sAN FRANcisco"; // Chill bro, let's make it consistent first const capitalized = city.toLowerCase().replace(/\b\w/g, c => c.toUpperCase()); // "San Francisco"

Using ES6 for the win

ES6 provides us arrow functions for a quicker and cleaner syntax. It's like riding a Tesla in string manipulation world:

const capitalizeWords = str => str.toLowerCase().replace(/\b\w/g, c => c.toUpperCase());

Slicing and dicing with split()

Another method involves slicing the string into words, capitalizing them individually, and then gluing them back again. Feels like a text-surgery, doesn't it?

// We are like 'string surgeons' here const capitalizeWords = str => str .toLowerCase() .split(' ') .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(' ');

Moving beyond JavaScript

Capitalizing in CSS land

Who doesn't love a multi-talented person? Using JavaScript, CSS can capitalize your strings:

.capitalize { text-transform: capitalize; }

And to dynamically apply this CSS property, you can sail back to JavaScript's boat:

element.style.textTransform = 'capitalize';

Dealing with edge cases

Complex names, simple solution

In this diverse world, some names just love to break the norms like "McDonald" or "O'Connell".

function complexCapitalization(str) { return str.toLowerCase().replace(/(^\w|\b\w(?<!['’]\w))/g, c => c.toUpperCase()); }

Struggles with non-standard delimiters

Who said a delimiter has to be a space? Cities like "New York-Newark" just love to be unique.

const capitalizeWords = str => str .toLowerCase() .replace(/(^\w|\b\w|-\w)/g, c => c.toUpperCase());

Culture-sensitive capitalization

Because each culture and language has its unique color.

Thinking about performance

Large datasets or high-frequency operations? Performance can drastically drop. Choose your method wisely!