0

Is there a way to summarize a replace function and make the code a bit cleaner? I haven't found a way to do this yet and cannot find an answer on here.

replaceFunction(string) {
        this.string = (encodeURIComponent(string.toLowerCase()
            .replace('/%[a-fA-F0-9]{2}/','-')
            .replace('/-+/','-')
            .replace('/-$/','')
            .replace('/^-/','')
            .replace('ä','ae')
            .replace('ö','oe')
            .replace('ü','ue')
            .replace('Ä','ae')
            .replace('Ö','oe')
            .replace('Ü','ue')
            .replace('_','-')
            .replace('.','-')
            .replace(/\s/g, '-')
            .replace(/["']/g, '')
        ));

        return string;
    }
networkcore
  • 135
  • 1
  • 11
  • 1
    Sample input, output? – User863 Sep 10 '19 at 12:27
  • You could try to put the replacements in a dictionary and iterate over that. Something like `[{s: 'ä', r: 'ae'}, {s: 'ö', r: 'oe'}]` and so on. Then you put your replace method in a loop and iterate over the dictionary. Another approach would be to iterate over your string character by character, and to replace stuff without using the replace method at all. – André Reichelt Sep 10 '19 at 12:27
  • I would write regex and replacement into object or array. and use forEach on object. – jcubic Sep 10 '19 at 12:35
  • 1
    Possible duplicate of [Replace multiple characters in one replace call](https://stackoverflow.com/questions/16576983/replace-multiple-characters-in-one-replace-call) – Federico klez Culloca Sep 10 '19 at 12:48

1 Answers1

0

You could try something similar to this (which is just a start, not the full implementation). This approach would also make it unnecessary to iterate over the string several times.

// First insert the polyfill posted here: https://stackoverflow.com/a/4314050/10406502

let a = 'Häberle-+Hänsle';

for(let i = 0; i < a.length; i++) {
  switch (a[i]) {
    case '-':
      if (i + 1 < a.length && a[i + 1] !== '+')
        break;
      a = a.splice(i + 1, 1, '');
      i--;
      break;
    case 'ä':
      a = a.splice(i, 1, 'ae');
      i++;
      break;
  }
}
André Reichelt
  • 1,484
  • 18
  • 52