Problems › JavaScript › text
Title-case a heading
The CMS title-cases headings on save, but the house style leaves the small joining words in lowercase unless one of them opens the heading.
- Capitalise the first letter of every word and lowercase the rest of it.
- These stay lowercase: a, an, and, as, at, but, by, for, in, of, on, or, the, to.
- Except the very first word, which is always capitalised.
- Words are separated by single spaces.
titleCase(heading: string) → string
Where you start
function titleCase(heading) {
}
Worked examples
| Call | Result |
|---|---|
titleCase("the lord of the rings") | "The Lord of the Rings" |
titleCase("a tale OF two cities") | "A Tale of Two Cities" |
titleCase("hello") | "Hello" |
titleCase("of mice and men") | "Of Mice and Men" |
Hint
Handle index 0 as its own case, then let the small-word list decide for the rest.
Reference solution in JavaScript
function titleCase(heading) {
const small = new Set(['a', 'an', 'and', 'as', 'at', 'but', 'by', 'for', 'in', 'of', 'on', 'or', 'the', 'to']);
if (heading === '') return '';
return heading.split(' ').map((w, i) => {
const low = w.toLowerCase();
if (i > 0 && small.has(low)) return low;
return low.charAt(0).toUpperCase() + low.slice(1);
}).join(' ');
}