Convert a string to title case in JavaScript
Intermediate · 4 min read
Title case means starting every word with a capital letter: 'the quick brown fox' becomes 'The Quick Brown Fox'. You see it in headings, product names, names in a contact list, and anywhere text typed in small letters needs to look tidy.
In this tutorial you will write a titleCase function that does this one word at a time. You will also try the popular one-line regex version and see why an apostrophe breaks it, turning don't into Don'T. You should know what an array is and have seen map.
The plan
There is no built-in title case method in JavaScript, so you build it from three smaller jobs:
- Cut the sentence into words.
- Capitalize the first letter of each word.
- Glue the words back together.
Capitalizing one word
To capitalize one word, take its first letter, make it upper case, and stick the rest of the word back on:
const word = 'quick';
console.log(word.charAt(0).toUpperCase()); // 'Q'
console.log(word.slice(1)); // 'uick'
console.log(word.charAt(0).toUpperCase() + word.slice(1)); // 'Quick'
charAt(0) is the first character. slice(1) is everything from position 1 onwards, the rest of the word. Only the first letter changes; the rest stays exactly as it was typed.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
15 Title case a sentence
fairTurn 'the quick brown fox' into 'The Quick Brown Fox'. Decide what an apostrophe should do, and preserve the spacing exactly.
Stuck? Three hints, smallest first
- 1. Split on spaces, capitalise each piece, join back with the same separator.
- 2. The one-line regex version capitalises after every word boundary, and an apostrophe is one.
- 3. Only the first letter changes: the rest of each word keeps whatever case it had.
Step 1: split the sentence into words
console.log('the quick brown fox'.split(' ')); // [ 'the', 'quick', 'brown', 'fox' ]
split(' ') cuts the text at every space and gives you an array of the pieces.
Step 2: capitalize every word and join them back
map runs a function on every item of an array and gives you a new array of the results. join(' ') glues the pieces back with a space between each.
const titleCase = (text) =>
text.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
console.log(titleCase('the quick brown fox')); // 'The Quick Brown Fox'
console.log(titleCase('lagos')); // 'Lagos'
That is the whole function. The rest of this tutorial is about how it treats awkward input.
Step 3: keep the spacing exactly
What if there are two spaces between words, or a space at the start?
const titleCase = (text) =>
text.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
console.log(JSON.stringify(titleCase('a b'))); // "A B"
console.log(JSON.stringify(titleCase(' lagos'))); // " Lagos"
console.log(JSON.stringify(titleCase(''))); // "", an empty string
Splitting 'a b' on a single space gives ['a', '', 'b']: there is an empty piece between the two spaces. Capitalizing an empty piece does nothing, because charAt(0) of an empty string is an empty string. So when you join back with spaces, both spaces return, and the original spacing is kept. JSON.stringify is only there so you can see the spaces in the output.
Step 4: an apostrophe
const titleCase = (text) =>
text.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
console.log(titleCase("don't stop")); // "Don't Stop"
"don't" is one piece, since there is no space inside it, so only its first letter changes. That is the right answer.
Step 5: the tempting one-liner
You will often see title case written as one regex replace:
const byWordBoundary = (text) => text.replace(/\b[a-z]/g, (c) => c.toUpperCase());
console.log(byWordBoundary('the quick brown fox')); // 'The Quick Brown Fox'
console.log(byWordBoundary("don't stop")); // "Don'T Stop"
In a regex, \b means a word boundary: a spot where a letter, digit or underscore sits next to anything else. [a-z] is one lower-case letter, and g means "every match". So the pattern finds every lower-case letter that starts a word, and the function upper-cases it.
It works on the first sentence. But an apostrophe isn't a letter, so there is a word boundary between ' and t in don't, and the t gets capitalized. That is why splitting on spaces is the safer plan for real sentences.
Step 6: what it leaves alone
const titleCase = (text) =>
text.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
console.log(titleCase('iPhone repair')); // 'IPhone Repair'
console.log(titleCase('LAGOS')); // 'LAGOS'
console.log(titleCase('Hi There')); // 'Hi There'
Only the first letter of each word changes. So iPhone becomes IPhone, and text in all capitals stays in all capitals. If you want 'LAGOS' to become 'Lagos', lower-case the rest of the word too: w.slice(1).toLowerCase(). That fixes shouting text but would turn iPhone into Iphone, so it depends on your data.
The full solution
Here is the complete answer: titleCase, the regex one-liner for comparison, and the awkward inputs from the steps. Press Run and compare the two "don't stop" lines.
const titleCase = (text) =>
text.split(' ').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
// The tempting one-liner. \b matches at every word boundary, and an apostrophe
// is not a word character, so there is a boundary right before the t in "don't".
const byWordBoundary = (text) => text.replace(/\b[a-z]/g, (c) => c.toUpperCase());
console.log(titleCase('the quick brown fox'));
console.log('titleCase("don\'t stop") :', titleCase("don't stop"));
console.log('byWordBoundary("don\'t stop") :', byWordBoundary("don't stop"), '<- the apostrophe fooled it');
console.log('titleCase("iPhone repair") :', titleCase('iPhone repair'));
Output
10 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('each word is capitalised', titleCase('the quick brown fox'), 'The Quick Brown Fox');
test('an empty string stays empty', titleCase(''), '');
test('the gap between words is preserved exactly', titleCase('a b'), 'A B');
test('already-capitalised text is unchanged', titleCase('Hi There'), 'Hi There');
test('an apostrophe does not start a new word', titleCase("don't stop"), "Don't Stop");
test('but the word-boundary version thinks it does', byWordBoundary("don't stop"), "Don'T Stop");
test('only the first letter changes, so camelCase survives oddly', titleCase('iPhone repair'), 'IPhone Repair');
test('and shouting text is left shouting', titleCase('LAGOS'), 'LAGOS');
test('one word is still title cased', titleCase('lagos'), 'Lagos');
test('a leading space produces an empty first word, harmlessly', titleCase(' lagos'), ' Lagos');
Splitting on a single space rather than on /\s+/ is the deliberate choice here: it keeps the original spacing, so 'a b' comes back with both spaces. Splitting on a run of whitespace would collapse them, which is a different job — exercise 62.
The word-boundary one-liner is shorter and wrong for real prose. "Don'T", "O'Brien" becoming "O'Brien" only by luck, and hyphenated names all come out of the same cause. Real title casing also lower-cases small words like "of" and "the" except at the start, which no one-liner does.
Common mistakes
- Using
/\b[a-z]/gon real text. Apostrophes create word boundaries, so you getDon'TandIt'S. - Splitting on
/\s+/when spacing matters. It merges runs of spaces, so'a b'comes back as'A B'. - Forgetting
join(' '). Without it you return an array, and plainjoin()puts commas between the words.
Try it yourself
- Change
titleCaseso'LAGOS IS BIG'becomes'Lagos Is Big'. - Keep small words like
ofandthein lower case, except when they are the first word:'the lord of the rings'should become'The Lord of the Rings'. - Write
capitalize(text)that only capitalizes the very first letter of a sentence.