Capitalize the first letter of each word in JavaScript
Beginner · 4 min read
Turning 'the quick brown fox' into 'The Quick Brown Fox' is called title case. You see it in headings, names in a contact list, product titles and the labels on buttons. People type names in all sorts of ways ('ada LOVELACE', ' lagos'), so tidying the capitals is a job that comes up in almost every form.
In this tutorial you will write capitalise(word) for a single word, then titleCase(sentence) for a whole sentence, then a second version, titleCaseRegex, that copes with any kind of spacing. You need to know what a string and a function are. Everything else is explained as we go.
Reading one character, and the rest
A string is a row of characters, and you can read them by position. Positions start at 0.
const word = 'lagos';
console.log(word[0]); // l
console.log(word.slice(1)); // agos
word[0] is the first character. word.slice(1) gives everything from position 1 to the end. Those two pieces, joined back together, make the whole word again.
Changing case
Two methods change the case of a string. Neither changes the original; each gives you a new string.
console.log('l'.toUpperCase()); // L
console.log('AGOS'.toLowerCase()); // agos
That is everything the exercise needs.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
24 Capitalise the first letter of each word
easyTurn a sentence into title case, with each word starting in upper case. Handle multiple spaces and already-capitalised text.
Stuck? Three hints, smallest first
- 1.
word[0].toUpperCase() + word.slice(1)capitalises one word. - 2. An empty word would make
word[0]undefined, so guard for it. - 3. Lowercase the rest of each word, or "hELLO" stays odd.
Step 1: capitalize one word
Upper-case the first character and glue the rest back on:
const capitalise = (word) => word[0].toUpperCase() + word.slice(1);
console.log(capitalise('lagos')); // Lagos
Now try a word with messy capitals:
const capitalise = (word) => word[0].toUpperCase() + word.slice(1);
console.log(capitalise('hELLO')); // HELLO
The first letter is right, but the rest was left as it was. Title case means the rest of the word should be lower case too.
Step 2: lower-case the rest
const capitalise = (word) => word[0].toUpperCase() + word.slice(1).toLowerCase();
console.log(capitalise('hELLO')); // Hello
Better. There is one more case to handle: a word with no characters at all.
const capitalise = (word) => word[0].toUpperCase() + word.slice(1).toLowerCase();
console.log(capitalise('')); // TypeError: Cannot read properties of undefined (reading 'toUpperCase')
An empty string has no character at position 0, so word[0] is undefined, and undefined has no toUpperCase method. The program crashes. That sounds unlikely, but you will see in Step 3 that empty words appear as soon as someone types two spaces.
Step 3: guard against the empty word
A guard is an early return that handles the awkward case before the main code runs:
function capitalise(word) {
if (word.length === 0) return word;
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
console.log(capitalise('lagos')); // Lagos
console.log(capitalise('')); // an empty string, no crash
Step 4: do every word
To handle a sentence, split it into words, capitalize each one with map, and join them back with spaces:
function titleCase(sentence) {
return sentence.split(' ').map(capitalise).join(' ');
}
console.log(titleCase('the quick brown fox')); // The Quick Brown Fox
console.log(titleCase('hELLO wORLD')); // Hello World
console.log(titleCase('a b')); // A B
map(capitalise) calls capitalise on every item and collects the results in a new array. Look at the last line. 'a b'.split(' ') gives ['a', '', 'b'], with an empty string between the two spaces. That empty string is why the guard in Step 3 matters. Without it, this line would crash.
Step 5: handle any whitespace
split(' ') only knows about ordinary spaces. A tab or a newline is just another character to it, so the word after a tab is never capitalized:
console.log(titleCase('one\ttwo')); // One two (two stays lower case)
replace with a regular expression solves this. The pattern /\S+/g matches every run of characters that are not whitespace, in other words every word. When you pass a function as the second argument, replace calls it with each match and puts the result in its place.
function titleCaseRegex(sentence) {
return sentence.replace(/\S+/g, capitalise);
}
console.log(titleCaseRegex('one\ttwo')); // One Two
console.log(titleCaseRegex('spaced out')); // Spaced Out
Only the words are touched. Every space, tab and newline stays exactly where it was, and since the pattern never matches an empty string, capitalise never sees one.
The full solution
The complete answer has capitalise, the split version and the regex version, and tries them on plain, messy and widely spaced text. Press Run to see the output.
function capitalise(word) {
if (word.length === 0) return word; // guard, or word[0] is undefined
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
function titleCase(sentence) {
return sentence.split(' ').map(capitalise).join(' ');
}
// The regex version, which handles any whitespace and keeps it intact.
function titleCaseRegex(sentence) {
return sentence.replace(/\S+/g, capitalise);
}
console.log(titleCase('the quick brown fox'));
console.log(titleCase('hELLO wORLD'));
console.log(titleCaseRegex('spaced out words'));
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain sentence', titleCase('the quick brown fox'), 'The Quick Brown Fox');
test('odd casing is normalised', titleCase('hELLO wORLD'), 'Hello World');
test('one word', capitalise('lagos'), 'Lagos');
test('empty text does not throw', capitalise(''), '');
test('the regex version keeps the spacing', titleCaseRegex('spaced out'), 'Spaced Out');
test('the split version collapses nothing but needs even spacing', titleCase('a b'), 'A B');
test('already correct stays correct', titleCase('Lagos Abuja'), 'Lagos Abuja');
capitalise('') is the case that matters: without the length guard, word[0] is undefined and .toUpperCase() throws. That happens as soon as your input has a double space, because split(' ') produces an empty string between them. The regex version sidesteps it by only matching runs of non-space, which also preserves the original spacing.
Common mistakes
- Forgetting to lower-case the rest.
'hELLO'becomes'HELLO'instead of'Hello'. - No guard for an empty word.
''[0]isundefined, and calling.toUpperCase()on it throws. A double space is enough to trigger it. - Expecting it to know about names. Lower-casing the rest turns
'NASA'into'Nasa'and'McDonald'into'Mcdonald'. If your text has names like these, title case needs a list of exceptions.
Try it yourself
- Write
capitaliseFirst(sentence)that only capitalizes the very first letter of the whole sentence, like the start of a normal sentence. - Change
titleCaseso it also trims spaces from the start and end of the sentence. - Keep small words like
ofandthein lower case, unless they are the first word:'the lord of the rings'becomes'The Lord of the Rings'.