From 5a8cab13061e3279d8c0f278a86b0e06f01f034d Mon Sep 17 00:00:00 2001 From: Andrew Patton Date: Tue, 23 Jan 2024 09:37:04 -0800 Subject: [PATCH] Ignore non-alphanumeric characters in getInitials --- packages/textual/src/index.test.ts | 4 ++++ packages/textual/src/index.ts | 11 +++++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/textual/src/index.test.ts b/packages/textual/src/index.test.ts index d938f604..3aa5d82d 100644 --- a/packages/textual/src/index.test.ts +++ b/packages/textual/src/index.test.ts @@ -62,6 +62,10 @@ describe('@acusti/text-transform', () => { it('ignores any extra whitespace in the input text', () => { expect(getInitials(' \nfranklin\t\t delano roosevelt \n ')).toBe('FDR'); }); + + it('ignores any non alphanumeric characters', () => { + expect(getInitials('**franklin delano !! roosevelt 3rd', 4)).toBe('FDR3'); + }); }); describe('getNameFromEmail', () => { diff --git a/packages/textual/src/index.ts b/packages/textual/src/index.ts index 5220614a..ccb6279d 100644 --- a/packages/textual/src/index.ts +++ b/packages/textual/src/index.ts @@ -10,8 +10,15 @@ export const capitalize = (text: string) => }, ); -export const getInitials = (name: string, maxLength = 3) => - name.replace(WORDS_REGEX, '$1').trim().substring(0, maxLength).toUpperCase(); +export const getInitials = (name: string, maxLength = 3) => { + let initials = ''; + const matches = name.matchAll(WORDS_REGEX); + for (const match of matches) { + initials += match[1].toUpperCase(); + if (initials.length >= maxLength) break; + } + return initials; +}; const EMAIL_SEPARATOR_REGEX = /[+.]/g;