Skip to content

Commit

Permalink
Ignore non-alphanumeric characters in getInitials
Browse files Browse the repository at this point in the history
  • Loading branch information
acusti committed Jan 23, 2024
1 parent e9c6481 commit 5a8cab1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
4 changes: 4 additions & 0 deletions packages/textual/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
11 changes: 9 additions & 2 deletions packages/textual/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down

0 comments on commit 5a8cab1

Please sign in to comment.