Simple utility to capitalize the first letter of a string.
export function capitalize(str: string): string {
return str.charAt(0).toUpperCase() + str.slice(1);
}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);
}
capitalize("luka"); // => "Luka"
capitalize("hello world"); // => "Hello world"
capitalize(""); // => ""
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();
}
Hope this utility helps you keep your strings tidy and readable!