QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Get Initials

Verified

Extracts up to N uppercase initials from a name, e.g. for avatar fallbacks.

  • string
  • initials
  • name

Install

npx shadcn@latest add https://quicksnip.dev/r/initials.json

Code

/** Returns up to `max` uppercase initials from a name, e.g. for avatar fallbacks. */
export function getInitials(name: string, max = 2): string {
  return name
    .trim()
    .split(/\s+/)
    .filter(Boolean)
    .slice(0, max)
    .map((part) => part[0].toUpperCase())
    .join("");
}

Usage

getInitials("Ada Lovelace");     // "AL"
getInitials("Mary Jane Watson"); // "MJ"