Multiple Regex replace

后端 未结 5 726
一生所求
一生所求 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:27

    You could do it like this:

    function clean(str) {
        var expressions = {
            '@~rb~@': '',
            '}':      '@~rb~@',
            // ...
        };
    
        for (var key in expressions) {
            if (expressions.hasOwnProperty(key)) {
                str = str.replace(new RegExp(key, 'g'), expressions[key]);
            }
        }
    
        return str;
    }
    

    Keep in mind that the order of object properties is not reliably determinable (but most implementations will return them in order of definition). You will probably need multiple constructs like this if you need to ensure a specific order.

提交回复
热议问题