Emmanuel Akinfulubi

JavaScriptBasic

Title case with small words (of, the) in JavaScript

Intermediate · 3 min read

Book and film titles follow a style called title case: most words start with a capital letter, but short joining words such as "of", "the" and "and" stay lower case. That is why it is "The Lord of the Rings" and not "The Lord Of The Rings". Blogs, shops and media sites use this to tidy up headings that people type in any old way.

In this tutorial you will write titleCase(sentence). It turns 'the lord of the rings' into 'The Lord of the Rings', and it also cleans up input typed in capitals or with extra spaces. You need to know what a string, an array and a function are.

The rule, in plain words

  1. Capitalize every word...
  2. ...except small words like "of", "the", "and", "a" and "to"...
  3. ...unless the small word is the first or last word. Those are always capitalized.

So 'of mice and men' becomes 'Of Mice and Men': "of" is first, so it gets a capital, and "and" sits in the middle, so it stays small. The rule about the last word is a common convention, and this exercise follows it.

Two tools: a Set and map with an index

A Set is a collection of values with fast lookups. has(value) answers true or false:

JavaScript

const SMALL = new Set(['of', 'the', 'and']);
console.log(SMALL.has('of'));   // true
console.log(SMALL.has('ring')); // false

map builds a new array by running a function on each item. That function also gets a second argument, the item's position, called the index, which starts at 0:

JavaScript

console.log(['a', 'b', 'c'].map((w, i) => w + i)); // [ 'a0', 'b1', 'c2' ]

The index is how you will spot the first and last word.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

43 Convert a string to title case, respecting small words

fair

Title-case a sentence, but leave short joining words such as "of" and "the" in lower case unless they start the title.

Stuck? Three hints, smallest first
  1. 1. Keep a set of words that stay lower case: articles, conjunctions and short prepositions.
  2. 2. The first word is always capitalised, whatever it is.
  3. 3. Many style guides also capitalise the last word. Decide and say so.

Step 1: capitalize one word

Take the first letter, make it upper case, and add the rest of the word in lower case:

Step 1

const cap = (w) => (w.length === 0 ? w : w[0].toUpperCase() + w.slice(1).toLowerCase());
console.log(cap('lord'));  // Lord
console.log(cap('RINGS')); // Rings

w[0] is the first character and w.slice(1) is everything after it. The length check stops an empty string from crashing: ''[0] is undefined, and undefined.toUpperCase() throws.

Step 2: split the sentence into clean words

People type titles in capitals and with double spaces. Lowercase everything first, then split on any run of whitespace:

Step 2

const words = 'a  tale   OF two'.toLowerCase().split(/\s+/).filter(Boolean);
console.log(words); // [ 'a', 'tale', 'of', 'two' ]

/\s+/ means "one or more whitespace characters", so three spaces count as one gap. filter(Boolean) removes any empty strings, which appear when the text starts or ends with a space, or when it is empty.

Step 3: the tempting version

Capitalize everything except small words:

JavaScript

const SMALL = new Set(['a', 'an', 'and', 'of', 'the', 'with']);
const cap = (w) => (w.length === 0 ? w : w[0].toUpperCase() + w.slice(1).toLowerCase());
const tryOne = (s) => s.split(' ').map((w) => (SMALL.has(w) ? w : cap(w))).join(' ');
console.log(tryOne('the lord of the rings')); // the Lord of the Rings

The first word stays small. That is the edge the rule warns about.

Step 4: always capitalize the edges

Use the index from map. A word is an edge if it is first (i === 0) or last (i === words.length - 1). Only words that are in the middle and small stay lower case:

Step 4

const SMALL = new Set(['a', 'an', 'and', 'as', 'at', 'but', 'by', 'for',
  'in', 'nor', 'of', 'on', 'or', 'the', 'to', 'up', 'via']);
const cap = (w) => (w.length === 0 ? w : w[0].toUpperCase() + w.slice(1).toLowerCase());
function titleCase(sentence) {
  const words = sentence.toLowerCase().split(/\s+/).filter(Boolean);
  return words
    .map((w, i) => {
      const isEdge = i === 0 || i === words.length - 1;
      return !isEdge && SMALL.has(w) ? w : cap(w);
    })
    .join(' ');
}
console.log(titleCase('the lord of the rings'));  // The Lord of the Rings
console.log(titleCase('of mice and men'));        // Of Mice and Men
console.log(titleCase('THE LORD OF THE RINGS'));  // The Lord of the Rings
console.log(titleCase('a  tale   of  two cities')); // A Tale of Two Cities
console.log(JSON.stringify(titleCase('')));       // ""

join(' ') glues the words back together with single spaces, so the extra spaces are gone. Empty input splits into no words and joins back to an empty string.

The full solution

The answer panel has the full list of small words, cap and titleCase, and prints four famous titles. The checks underneath cover the first and last word, shouty capitals, extra spaces and empty input. Press Run to see the output.

The answer

const SMALL = new Set(['a', 'an', 'and', 'as', 'at', 'but', 'by', 'for',
  'in', 'nor', 'of', 'on', 'or', 'the', 'to', 'up', 'via']);

const cap = (w) => (w.length === 0 ? w : w[0].toUpperCase() + w.slice(1).toLowerCase());

function titleCase(sentence) {
  const words = sentence.toLowerCase().split(/\s+/).filter(Boolean);
  return words
    .map((w, i) => {
      // First and last always capitalised; small words in between are not.
      const isEdge = i === 0 || i === words.length - 1;
      return !isEdge && SMALL.has(w) ? w : cap(w);
    })
    .join(' ');
}

const samples = [
  'the lord of the rings',
  'a tale of two cities',
  'gone with the wind',
  'of mice and men',
];

for (const s of samples) console.log(titleCase(s));

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.

7 checks

test('small words stay lower', titleCase('the lord of the rings'), 'The Lord of the Rings');
test('the first word is always capitalised', titleCase('of mice and men'), 'Of Mice and Men');
test('and so is the last', titleCase('gone with the wind'), 'Gone With the Wind');
test('a single small word', titleCase('the'), 'The');
test('mixed input is normalised first', titleCase('THE LORD OF THE RINGS'), 'The Lord of the Rings');
test('extra spaces collapse', titleCase('a  tale   of  two cities'), 'A Tale of Two Cities');
test('empty input', titleCase(''), '');

The rule "first and last are always capitalised" is a real convention rather than a convenience, and it is why 'of mice and men' becomes 'Of Mice and Men' with a capital O. Note the input is lowercased first, so a title arriving in shouty caps is normalised rather than left alone — without that, 'THE LORD OF THE RINGS' would come back unchanged.

Common mistakes

  • Forgetting the first word. A title that starts with "the" or "a" comes out starting with a small letter.
  • Not lowercasing the input first. 'THE LORD OF THE RINGS' doesn't match 'the' in the set, so every word is treated as a big word and the title comes back with "Of" and "The" in the middle.
  • Splitting on ' '. Double spaces leave empty strings in the array, and join puts the extra spaces back.

Try it yourself

  1. Add 'from' and 'into' to the small words and try 'escape from the planet of the apes'.
  2. Change the rule so only the first word is always capitalized, and see what happens to 'gone with the wind'.
  3. Keep words that are already all capitals, like 'NASA', as they are. (Hint: check the original word before lowercasing.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.