How to capitalize the first letter of each word, like a 2-word city?
Use .replace(/\b\w/g, c => c.toUpperCase())
to capitalize each word in a string:
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:
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:
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?
Moving beyond JavaScript
Capitalizing in CSS land
Who doesn't love a multi-talented person? Using JavaScript, CSS can capitalize your strings:
And to dynamically apply this CSS property, you can sail back to JavaScript's boat:
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".
Struggles with non-standard delimiters
Who said a delimiter has to be a space? Cities like "New York-Newark" just love to be unique.
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!
Was this article helpful?