Multiple Regex replace

后端 未结 5 727
一生所求
一生所求 2021-01-17 11:24

I am boggled by regex I think I\'m dyslexic when it comes to these horrible bits of code.. anyway, there must be an easier way to do this- (ie. list a set of replace instanc

5条回答
  •  遇见更好的自我
    2021-01-17 11:32

    You can define either a generic function, which would make sense if you can reuse it in more parts of your code, thus making it DRY. If you don't have reason to define a generic one, I would compress only the part which cleans sequences and leave the other replaces as they are.

    function clean(string) {
        string = string.replace(/\@~rb~@|\@~lb~@|\@~qu~@|\@~cn~@|\@-cm-@/g, '')
          .replace(/}/g, '@~rb~@').replace(/{/g, '@~lb~@')
          .replace(/\"/g, '@~qu~@').replace(/\:/g, '@~cn~@')
          .replace(/\,/g, '@-cm-@');
        return string;
    }
    

    But be careful, the order of the replacements were changed it in this code.. although it seems they might not affect the result.

提交回复
热议问题