TypeScript

Capitalize / Title-Case

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Two common case transforms. `capitalize` for the first letter only; `titleCase` for every word, with small "stop words" left lowercase except at the edges.
TypeScript
Raw
export const capitalize = (s: string): string =>
  s.length === 0 ? s : s[0]!.toUpperCase() + s.slice(1);

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

export function titleCase(s: string): string {
  const words = s.toLowerCase().trim().split(/\s+/);
  return words.map((w, i) =>
    i === 0 || i === words.length - 1 || !STOP.has(w) ? capitalize(w) : w
  ).join(' ');
}

capitalize('hello world');          // 'Hello world'
titleCase('the lord of the rings'); // 'The Lord of the Rings'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.