capitalize
Capitalizes the first letter of a string. If strict
is true, lowercases the rest of the string.
1/**
2 * Capitalizes the first letter of a string.
3 * If 'strict' is true, lowercases the rest of the string.
4 *
5 * @param str - The input string.
6 * @param strict - Whether to lowercase the rest of the string (default: false).
7 * @returns A new string with the first letter capitalized.
8 */
9export function capitalize(str: string, strict = false): string {
10 if (!str) return '';
11 const first = str[0].toUpperCase();
12 const rest = strict ? str.slice(1).toLowerCase() : str.slice(1);
13 return first + rest;
14}
Flexible Capitalization Style
Supports both standard (capitalize only first letter) and strict mode (capitalize first, lowercase rest), allowing for a broader range of formatting needs.
Safe Fallback
Gracefully handles empty strings, avoiding runtime errors or unexpected output.
Lightweight and Fast
Minimal logic, optimal performance for real-time string formatting.
Pure Function
No side effects; always returns a new string, preserving immutability.
Tests | Examples
1test('capitalize - default behavior (strict = false)', () => {
2 expect(capitalize('hello')).toBe('Hello');
3 expect(capitalize('hELLo')).toBe('HELLo');
4});
5
6test('capitalize - strict = true', () => {
7 expect(capitalize('hello', true)).toBe('Hello');
8 expect(capitalize('hELLo', true)).toBe('Hello');
9});
10
11test('capitalize - already capitalized', () => {
12 expect(capitalize('Hello')).toBe('Hello');
13});
14
15test('capitalize - single lowercase letter', () => {
16 expect(capitalize('a')).toBe('A');
17});
18
19test('capitalize - single uppercase letter', () => {
20 expect(capitalize('A')).toBe('A');
21});
22
23test('capitalize - empty string', () => {
24 expect(capitalize('')).toBe('');
25});
26
27test('capitalize - non-letter characters', () => {
28 expect(capitalize('123abc')).toBe('123abc');
29 expect(capitalize('!hello', true)).toBe('!hello');
30});
Common Use Cases
Displaying User Names
Format names like
john
→John
orjOhN
→John
(withstrict = true
).Generating Titles or Labels
Capitalize form field labels, UI buttons, or generated section titles.
Data Normalization
Preprocess input for consistent storage or display — especially helpful in admin dashboards or reporting tools.
Sentence Formatting
Capitalize the first word of a sentence when building strings dynamically from keywords or fragments.
Sanitizing User Input
Standardize the format of user-submitted text before saving or comparing it.