Function to capitalize each word in JavaScript
Beginner · 4 min read
Turning 'the quick brown fox' into 'The Quick Brown Fox' is something websites do all the time: names typed in lower case on a sign-up form, product titles, headings built from user input. JavaScript has toUpperCase() for a whole string, but nothing built in for "the first letter of each word".
In this tutorial you will write a function called capitaliseWords that capitalizes every word. Then you will see a one-pass version using a regular expression, and a "title case" version that leaves small words like "of" alone. You need to know what a function, a string and an array are.
The pieces you need
Three string tools do all the work here. text[0] reads the first character. toUpperCase() makes text capital. slice(1) gives everything from position 1 to the end, so everything except the first character:
const word = 'lagos';
console.log(word[0].toUpperCase()); // 'L'
console.log(word.slice(1)); // 'agos'
console.log(word[0].toUpperCase() + word.slice(1)); // 'Lagos'
That last line capitalizes one word. The rest of the exercise is doing it for every word.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
5 Capitalise the first letter of each word
easy'the quick brown fox' should give 'The Quick Brown Fox'. The expected output has a trailing space; decide whether you want that.
Stuck? Three hints, smallest first
- 1. Split on spaces, capitalise each piece, join back.
- 2. A regex with a capture group does it in one pass:
replace(/\b\w/g, ...). - 3. Real title case leaves small words like "of" and "the" lower case, except at the ends.
Step 1: split into words, fix each one, join back
split(' ') cuts a sentence at every space and gives you an array of words. map runs a function on each word and collects the results in a new array. join(' ') puts the words back together with single spaces:
const words = 'the quick brown fox'.split(' ');
console.log(words); // [ 'the', 'quick', 'brown', 'fox' ]
const fixed = words.map((w) => w[0].toUpperCase() + w.slice(1));
console.log(fixed.join(' ')); // 'The Quick Brown Fox'
The exercise's expected output ends with an extra space: 'The Quick Brown Fox '. That kind of space comes from building the result in a loop with word + ' '. join(' ') only puts spaces between words, so there is no space at the end. That is usually what you want, because a hidden trailing space makes two texts look equal on screen while === says they differ.
Step 2: empty words and shouting
Two inputs break Step 1. Two spaces in a row make an empty word '', and ''[0] is undefined, which has no toUpperCase. And text typed in capitals, like 'THE QUICK fOX', stays shouty, because Step 1 only changes the first letter.
The answer handles both: it leaves an empty word alone, and it makes the rest of each word lower case:
const capitaliseWords = (text) =>
text.split(' ').map((w) => (w === '' ? w : w[0].toUpperCase() + w.slice(1).toLowerCase())).join(' ');
console.log(capitaliseWords('the quick brown fox')); // 'The Quick Brown Fox'
console.log(capitaliseWords('THE QUICK fOX')); // 'The Quick Fox'
console.log(capitaliseWords('')); // ''
The ? : is the conditional operator: condition ? valueIfTrue : valueIfFalse. Here it says "if the word is empty, keep it, otherwise capitalize it".
Step 3: one pass with a regular expression
A regular expression is a pattern for finding text. replace can take one and call a function for every match:
const capitaliseByRegex = (text) => text.toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
console.log(capitaliseByRegex('the quick brown fox')); // 'The Quick Brown Fox'
console.log(capitaliseByRegex('mary-jane watson')); // 'Mary-Jane Watson'
console.log(capitaliseWords('mary-jane watson')); // 'Mary-jane Watson'
\w means one letter, digit or underscore. \b means a word boundary, the point where a word starts or ends. So \b\w matches the first character of every word, and g means "all of them".
The last two lines show a real difference. To the regex, a hyphen ends a word, so jane gets a capital too. Splitting on spaces sees mary-jane as one word. Neither is wrong, but for names the hyphenated version is usually what people expect.
Step 4: real title case
Book and film titles usually keep small words in lower case: "The Lord of the Rings". But the first and last word are always capitalized, even when small. The answer keeps the small words in a Set and checks each word's position:
const SMALL = new Set(['a', 'an', 'the', 'of', 'to', 'and', 'or', 'in', 'on', 'at', 'for']);
function titleCase(text) {
const words = text.toLowerCase().split(' ').filter(Boolean);
return words
.map((w, i) =>
i !== 0 && i !== words.length - 1 && SMALL.has(w) ? w : w[0].toUpperCase() + w.slice(1))
.join(' ');
}
console.log(titleCase('the lord of the rings')); // 'The Lord of the Rings'
console.log(titleCase('the lord')); // 'The Lord'
map gives the function a second value, i, the position of the word. filter(Boolean) drops the empty words that extra spaces create, which is why 'the lord' comes out clean.
The full solution
The panel has all three functions: capitaliseWords, capitaliseByRegex and titleCase. It prints each one on the example, the hyphenated name both ways and two title-case examples. Press Run to compare them.
// Every word, no exceptions. Note the rest is lower-cased, so 'fOX' is fixed too.
const capitaliseWords = (text) =>
text.split(' ').map((w) => (w === '' ? w : w[0].toUpperCase() + w.slice(1).toLowerCase())).join(' ');
// One pass with a regex. \b is a word boundary, so it catches after a hyphen too.
const capitaliseByRegex = (text) => text.toLowerCase().replace(/\b\w/g, (c) => c.toUpperCase());
// Real title case: small words stay lower, but never the first or last word.
const SMALL = new Set(['a', 'an', 'the', 'of', 'to', 'and', 'or', 'in', 'on', 'at', 'for']);
function titleCase(text) {
const words = text.toLowerCase().split(' ').filter(Boolean);
return words
.map((w, i) =>
i !== 0 && i !== words.length - 1 && SMALL.has(w) ? w : w[0].toUpperCase() + w.slice(1))
.join(' ');
}
console.log("capitaliseWords :", JSON.stringify(capitaliseWords('the quick brown fox')));
console.log('the expected output:', JSON.stringify('The Quick Brown Fox '), '<- with a trailing space');
console.log('capitaliseByRegex:', JSON.stringify(capitaliseByRegex('the quick brown fox')));
console.log('a hyphenated name:', capitaliseByRegex('mary-jane watson'));
console.log('with map instead :', capitaliseWords('mary-jane watson'), '<- the hyphen is not a boundary here');
console.log('real title case :', titleCase('the lord of the rings'));
console.log('and at the ends :', titleCase('a tale of two cities and'));
Output
15 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 15 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', capitaliseWords('the quick brown fox'), 'The Quick Brown Fox');
test('with no trailing space, unlike the expected output', capitaliseWords('the quick brown fox').endsWith(' '), false);
test('shouting is normalised', capitaliseWords('THE QUICK fOX'), 'The Quick Fox');
test('a single word', capitaliseWords('lagos'), 'Lagos');
test('an empty string', capitaliseWords(''), '');
test('already capitalised stays that way', capitaliseWords('Lagos Abuja'), 'Lagos Abuja');
test('the regex version agrees on plain words', capitaliseByRegex('the quick brown fox'), 'The Quick Brown Fox');
test('but it also capitalises after a hyphen', capitaliseByRegex('mary-jane watson'), 'Mary-Jane Watson');
test('whereas the split version does not', capitaliseWords('mary-jane watson'), 'Mary-jane Watson');
test('which is a real difference, not a bug in either', capitaliseByRegex('mary-jane watson') === capitaliseWords('mary-jane watson'), false);
test('title case keeps small words lower', titleCase('the lord of the rings'), 'The Lord of the Rings');
test('but capitalises the first word even if small', titleCase('the rings'), 'The Rings');
test('and the last word too', titleCase('a tale of two cities and'), 'A Tale of Two Cities And');
test('a single small word is still capitalised', titleCase('the'), 'The');
test('extra spaces are collapsed by the title-case version', titleCase('the lord'), 'The Lord');
The expected output is 'The Quick Brown Fox ' with a trailing space, which is an artefact of building the result by appending word + ' ' in a loop. join(' ') avoids it, and the assertion checks there is no trailing space — worth being deliberate about, since a trailing space survives into your database and breaks comparisons later.
The two implementations genuinely differ, and the assertion proves it: w treats a hyphen as a word boundary, so 'mary-jane' becomes 'Mary-Jane', while splitting on spaces gives 'Mary-jane'. Neither is wrong; for names the hyphenated version is usually what people want.
titleCase is what you would want for a heading. The rule that small words stay lower except at either end is the part people leave out, and it is why 'The Rings' and '…Cities And' are both asserted.
Common mistakes
- Building the result with
word + ' 'in a loop. You get a trailing space. Usejoin(' '). - Forgetting to lower-case the rest.
'fOX'becomes'FOX'instead of'Fox'. Addslice(1).toLowerCase(). - Calling
w[0].toUpperCase()on an empty word. Two spaces in a row create one, andundefined.toUpperCase()throws a TypeError.
Try it yourself
- Run
capitaliseWords('hello world')with two spaces and check that the double space is still there. - Add
'but'and'with'toSMALLand testtitleCase('pride and prejudice with zombies'). - Write
capitaliseFirst(text)that capitalizes only the first letter of the whole sentence.