Skip to content
jshacks.dev
Fundamentals

Capitalize every word

Capitalize every word in a string, and see why the word-boundary regex turns it's into It'S and node.js into Node.Js. Node.js 18 and later.

2 min read
Summarize in AI

The first regex everyone writes for title case matches a word character at a word boundary, and it breaks on apostrophes and dots. The cause is how a boundary is defined, and Node.js 24 prints the result below.

JavaScript
const title = "it's a node.js world";

console.log(title.replace(/\b\w/g, (c) => c.toUpperCase()));
console.log(title.replace(/(^|\s)\S/g, (c) => c.toUpperCase()));
console.log(title.split(' ').map((w) => w[0].toUpperCase() + w.slice(1)).join(' '));
console.log('élan vital'.replace(/(^|\s)\S/gu, (c) => c.toUpperCase()));
Text
It'S A Node.Js World
It's A Node.js World
It's A Node.js World
Élan Vital

A word boundary sits wherever a word character meets a non-word one, and an apostrophe or a dot counts as non-word, so it's has a boundary before the s and node.js has one before js. The first output line shows it: It'S A Node.Js World. Matching the start of the string or a space followed by a non-space capitalizes only real word starts, as the second line shows. The split version on the third line gives the same text but has a trap of its own: two spaces in a row produce an empty word, and w[0].toUpperCase() throws TypeError: Cannot read properties of undefined (reading 'toUpperCase') on it. toUpperCase() handles accented letters, so élan becomes Élan, as the last line shows. The replacement function is called as the specification for String.prototype.replace describes.

This does not know English title rules, where of and the stay lowercase, and a few Unicode letters such as ß change length when uppercased. For display only, the CSS text-transform: capitalize does the same thing without touching the data.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.