Explorar el Código

fix(common): Contract multiple sequential replacers to just one in normalizeString (#3289)

Jeremy Milledge hace 1 año
padre
commit
f362a4b6ef

+ 7 - 0
packages/common/src/normalize-string.spec.ts

@@ -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');
+    });
 });

+ 4 - 1
packages/common/src/normalize-string.ts

@@ -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')
@@ -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);
 }