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;