avatar

Le Do Nghiem

Software Engineer

  • About me
  • Books
  • Snippets
  • Blog

© 2026 Le Do Nghiem. All rights reserved.

Contact |

Back to Snippets

Capitalize Function

Simple utility to capitalize the first letter of a string.

LanguageTypeScript
Last UpdatedApr 16, 2025
capitalize.ts
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);
}

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!

Previous Snippet

assertNever Utility

Next Snippet

Type Guard Utility