Skip to content

Commit

Permalink
fix(common): Contract multiple sequential replacers to just one in no…
Browse files Browse the repository at this point in the history
…rmalizeString (#3289)
  • Loading branch information
jezzzm authored Dec 30, 2024
1 parent e61abe6 commit f362a4b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
7 changes: 7 additions & 0 deletions packages/common/src/normalize-string.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,11 @@ describe('normalizeString()', () => {
it('replaces combining diaeresis with e', () => {
expect(normalizeString('Ja quäkt Schwyz Pöbel vor Gmünd')).toBe('ja quaekt schwyz poebel vor gmuend');
});

it('contracts multiple sequential replacers to a single replacer', () => {
expect(normalizeString('foo - bar', '-')).toBe('foo-bar');
expect(normalizeString('foo--bar', '-')).toBe('foo-bar');
expect(normalizeString('foo - bar', '_')).toBe('foo_-_bar');
expect(normalizeString('foo _ bar', '_')).toBe('foo_bar');
});
});
5 changes: 4 additions & 1 deletion packages/common/src/normalize-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
* Based on https://stackoverflow.com/a/37511463/772859
*/
export function normalizeString(input: string, spaceReplacer = ' '): string {
const multipleSequentialReplacerRegex = new RegExp(`([${spaceReplacer}]){2,}`, 'g');

return (input || '')
.normalize('NFD')
.replace(/[\u00df]/g, 'ss')
Expand All @@ -12,5 +14,6 @@ export function normalizeString(input: string, spaceReplacer = ' '): string {
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.replace(/[!"£$%^&*()+[\]{};:@#~?\\/,|><`¬'=©®]/g, '')
.replace(/\s+/g, spaceReplacer);
.replace(/\s+/g, spaceReplacer)
.replace(multipleSequentialReplacerRegex, spaceReplacer);
}

0 comments on commit f362a4b

Please sign in to comment.