How Lodash _.capitalize Works in JavaScript
The _.capitalize function in the Lodash utility library
standardizes string formatting by enforcing strict case transformation.
Rather than simply capitalizing the first letter and leaving the rest of
the string untouched, the method enforces a dual-action rule: it
converts the very first character of the input to uppercase while
forcing all subsequent characters into lowercase. This article details
the specific capitalization rules, edge cases, and behavior enforced by
_.capitalize.
1. Uppercasing the First Character
The primary rule of _.capitalize is transforming index
0 of the string to uppercase. If the initial character is
an alphabetic character, it is converted to its capital equivalent.
_.capitalize('fred'); // => 'Fred'2. Lowercasing All Subsequent Characters
A common misconception is that _.capitalize acts as a
non-destructive initial-letter capitalizer. In reality, it strictly
enforces that every character from index 1 to the end of
the string is converted to lowercase. Any existing uppercase letters,
acronyms, or camelCase conventions are overwritten.
- All-caps strings:
_.capitalize('FRED')results in'Fred'. - CamelCase strings:
_.capitalize('fooBar')results in'Foobar'. - Multi-word strings:
_.capitalize('hello WORLD')results in'Hello world'. Only the first word's initial character is capitalized; subsequent words remain entirely lowercase.
3. Non-Alphabetic Leading Characters
When the first character is not a letter—such as a number, whitespace, symbol, or punctuation mark—it cannot be converted to uppercase. In these scenarios, the first character remains unchanged, but the second rule still applies to the rest of the string. Every subsequent letter is converted to lowercase.
_.capitalize('100MB'); // => '100mb'
_.capitalize(' apple'); // => ' apple' (leading space prevents capitalization)
_.capitalize('--FOO--'); // => '--foo--'4. Coercion and Nullish Values
Lodash safely handles non-string and missing values by converting inputs to strings internally before applying capitalization:
- Passing
nullorundefinedreturns an empty string''. - Non-string primitives (such as booleans or numbers) are converted to
their string representations and processed according to the rules:
_.capitalize(true)evaluates to'True'.