Drill

ProblemsJavaScript › text

Title-case a heading

mediumtextJavaScript

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.

titleCase(heading: string) → string

Solve it in the editor →

Where you start

function titleCase(heading) {
  
}

Worked examples

CallResult
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(' ');
}

The same problem in another language

More text problems in JavaScript