capitalizeEachWord
Capitalizes the first letter of each word in a string.
1/**
2 * Capitalizes the first letter of each word in a string.
3 *
4 * @param str - The input string.
5 * @returns A new string with each word's first character capitalized.
6 */
7export function capitalizeEachWord(str: string): string {
8 return str.replace(/\b\w/g, char => char.toUpperCase());
9}
Regex-Based Efficiency
Uses a compact and efficient regular expression (
\b\w
) to target word boundaries, ensuring broad language support and fast execution.Simple and Readable Implementation
Easy to understand and integrate into larger formatting pipelines.
Non-destructive Transformation
Only the first letter of each word is altered, preserving the rest of the word’s original casing (can be layered with
.toLowerCase()
if stricter formatting is needed).
Tests | Examples
1test('capitalizeEachWord - basic sentence', () => {
2 expect(capitalizeEachWord('hello world')).toBe('Hello World');
3});
4
5test('capitalizeEachWord - multiple spaces', () => {
6 expect(capitalizeEachWord(' multiple spaces here'))
7 .toBe(' Multiple Spaces Here');
8});
9
10test('capitalizeEachWord - mixed case', () => {
11 expect(capitalizeEachWord('javaScript IS awesome'))
12 .toBe('JavaScript IS Awesome');
13});
14
15test('capitalizeEachWord - numbers and symbols', () => {
16 expect(capitalizeEachWord('123 go! this is @test'))
17 .toBe('123 Go! This Is @Test');
18});
19
20test('capitalizeEachWord - empty string', () => {
21 expect(capitalizeEachWord('')).toBe('');
22});
23
24test('capitalizeEachWord - single word', () => {
25 expect(capitalizeEachWord('example')).toBe('Example');
26});
Common Use Cases
Formatting Titles or Headlines
Convert strings like
"the quick brown fox"
→"The Quick Brown Fox"
for display in blogs, news apps, or product names.Improving Readability of Raw Input
Reformat database or API responses to be more human-readable — e.g.,
"john doe"
→"John Doe"
.Auto-formatting Form Inputs
Automatically capitalize names or addresses in real-time as users type (e.g., billing forms or contact pages).
Generating UI Labels
Useful when creating labels dynamically from field names or keys like
"user_name"
→"User_Name"
→"User Name"
→"User Name"
.Custom Report Generation
Helpful in dashboards, analytics, or PDF exports where display formatting matters.