Capitalize Function
April 16, 2025
Sometimes, you need to ensure that a string starts with an uppercase letter — for example, when displaying names, titles, or labels. Here's a simple utility function in TypeScript to do just that:
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}
How It Works
- str.charAt(0) gets the first character of the string.
- .toUpperCase() capitalizes it.
- str.slice(1) gets the rest of the string.
- Finally, we concatenate them to get the result.
Example
capitalize("luka"); // => "Luka"
capitalize("hello world"); // => "Hello world"
capitalize(""); // => ""
Note
This function does not change the casing of the rest of the string — only the first character. If you want to fully normalize a string (like capitalize("hELLo") → "Hello"), you'll need a more advanced version:
export function capitalizeFull(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
When to Use
- Capitalizing names: capitalize("john") → "John"
- Formatting user input
- Displaying titles or UI labels cleanly
Hope this utility helps you keep your strings tidy and readable!