JavaScript Snippet

Capitalize the First Letter

Difficulty: Easy

Capitalising the first letter of a string is a tiny task that hides several gotchas: empty inputs, multi-word phrases, and Unicode characters whose uppercase form is more than one code unit. This snippet starts with the obvious one-liner, hardens it against `null`/`undefined`/empty strings, then upgrades to a code-point-safe variant and finally a per-word title-case helper. Drop these in for form labels, headings, and CSV column titles.

Code Snippets
/

Capitalize the First Letter

Capitalize the First Letter

Capitalising the first letter of a string is a tiny task that hides several gotchas: empty inputs, multi-word phrases, and Unicode characters whose uppercase form is more than one code unit. This snippet starts with the obvious one-liner, hardens it against `null`/`undefined`/empty strings, then upgrades to a code-point-safe variant and finally a per-word title-case helper. Drop these in for form labels, headings, and CSV column titles.

JavaScript
Easy
4 snippets
strings
utility
code-template

454 views

12

The classic two-step uppercases the first character with charAt(0).toUpperCase() and concatenates slice(1) for the rest. Using charAt(0) over str[0] matters for the empty-string case because charAt returns '' whereas str[0] returns undefined, which would stringify to 'undefined' and break the output. This implementation runs in O(n) because slice copies the tail, but the constant factor is tiny and good enough for typical UI strings. Reach for it when you control the input and just need to fix one form label.