getInitials
getInitials derives consistent, uppercase initials from a person’s display name. Use it anywhere you need initials from a name — avatar fallbacks, user lists, comment threads, table cells, or custom layouts.
Import
import { getInitials } from "@cfa/react-core";Features
- Derives 1–2 uppercase initials from a display name
- Treats hyphens and whitespace as word separators
- Ignores leading punctuation or symbols within each word
- Returns an empty string for blank or unusable input
Usage
import { getInitials } from "@cfa/react-core";
getInitials("Truett Cathy"); // "TC"getInitials("Mary Ann Smith"); // "MS"With Avatar
Avatar.Fallback does not derive initials from a name automatically. Pass the result of getInitials as fallback content:
import { Avatar, getInitials } from "@cfa/react-core";
<Avatar.Root aria-label="Truett Cathy"> <Avatar.Fallback>{getInitials("Truett Cathy")}</Avatar.Fallback></Avatar.Root>;See Avatar for more composition patterns.
Examples
| Input | Output | Notes |
|---|---|---|
"Truett Cathy" | "TC" | Standard first + last |
"Mary Ann Smith" | "MS" | Middle names ignored |
" John Doe " | "JD" | Whitespace trimmed and normalized |
"Madonna" | "M" | Single-word name |
"Mary-Jane" | "MJ" | Hyphenated first name |
"Mary-Jane Watson" | "MW" | Hyphen splits, then first + last |
"Jean-Luc Picard" | "JP" | Hyphenated given name + surname |
"Sean O'Brien" | "SO" | Apostrophe stays attached to the word |
"O'Brien" | "O" | Mononym with apostrophe |
"@John Doe" | "JD" | Leading @ stripped per word |
"...Jane" | "J" | Leading punctuation stripped |
"", " ", "!!!", "---" | "" | No usable letters |
When to pass explicit initials
getInitials does not parse titles or name suffixes. Override manually when the display name includes honorifics, generational suffixes, or credentials you do not want reflected in the initials:
| Input | Derived | Recommended |
|---|---|---|
"John Doe Jr." | "JJ" | Pass "JD" |
"Dr. Jane Smith" | "DS" | Pass "JS" |
API
getInitials(name: string): stringParameters
name— Display name to derive initials from. Use the same string shown to the user, such as a profile full name.
Returns
- An empty string when the name is blank or has no usable letters; otherwise one or two uppercase letters (for example,
"M"or"TC").