Skip to content
GreenSnippets

Capitalize and title-case strings

Uppercase the first letter of a string or of every word, leaving the rest of each word untouched.

JavaScript
const capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);

const titleCase = (text) =>
  text.toLowerCase().replace(/(^|\s)(\S)/g, (_, space, char) => space + char.toUpperCase());

Example / expected output

Output
capitalize("hello world")  // "Hello world"
titleCase("hELLO wORLD")   // "Hello World"

How it works

capitalize only touches the first character. titleCase capitalizes each whitespace-separated word and lowercases the rest. It is a simple rule: it does not know English small words ("of", "the") or acronyms.