Skip to content

Commit

Permalink
Improve getInitials for single-word names (+tests)
Browse files Browse the repository at this point in the history
  • Loading branch information
acusti committed Mar 15, 2024
1 parent 0de5017 commit 34e35cc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
12 changes: 12 additions & 0 deletions packages/textual/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@ describe('@acusti/text-transform', () => {
expect(getInitials('Jamie-Lee Curtis')).toBe('JLC');
});

it('for single-word names, uses the first letter/number and any uppercase letters or numbers as initials', () => {
expect(getInitials('Cat')).toBe('C');
expect(getInitials('CAT')).toBe('CAT');
expect(getInitials('C4t')).toBe('C4');
expect(getInitials('C4T')).toBe('C4T');
expect(getInitials('BigO')).toBe('BO');
expect(getInitials(' "LastPass"')).toBe('LP');
expect(getInitials(' "LastP4ss"')).toBe('LP4');
// if initials would be only numbers, include 1st letter (if present)
expect(getInitials('4ty')).toBe('4T');
});

it('ignores any extra whitespace in the input text', () => {
expect(getInitials(' \nfranklin\t\t delano roosevelt \n ')).toBe('FDR');
});
Expand Down
14 changes: 14 additions & 0 deletions packages/textual/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const WORDS_REGEX = /\b([a-zA-Z0-9])([^\s.-]*)([\s.-]*)/g;
const SINGLE_WORD_NON_INITIALS_REGEX = /(^[^A-Za-z0-9]+|[^A-Z0-9]+)/g;

// Returns text with equivalent formatting to text-transform: capitalize
export const capitalize = (text: string) =>
Expand All @@ -11,7 +12,20 @@ export const capitalize = (text: string) =>
);

export const getInitials = (name: string, maxLength = 3) => {
name = name.trim();
if (!name) return '';

let initials = '';
// for single word names, use uppercase letters and numbers
if (!name.includes(' ')) {
initials = name.replace(SINGLE_WORD_NON_INITIALS_REGEX, '').substring(0, maxLength);
// if initials are only numbers, include 1st letter (if present)
if (!/[a-zA-Z]/.test(initials)) {
initials += name.replace(/[^A-Za-z]+/, '')[0];
}
return initials.substring(0, maxLength).toUpperCase();
}

const matches = name.matchAll(WORDS_REGEX);
for (const match of matches) {
initials += match[1].toUpperCase();
Expand Down

0 comments on commit 34e35cc

Please sign in to comment.