Multiple Regex replace

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

    You could use a function replacement. For each match, the function decides what it should be replaced with.

    function clean(string) {
        // All your regexps combined into one:
        var re = /@(~lb~|~rb~|~qu~|~cn~|-cm-)@|([{}":,])/g;
    
        return string.replace(re, function(match,tag,char) {
            // The arguments are:
            // 1: The whole match (string)
            // 2..n+1: The captures (string or undefined)
            // n+2: Starting position of match (0 = start)
            // n+3: The subject string.
            // (n = number of capture groups)
    
            if (tag !== undefined) {
                // We matched a tag. Replace with an empty string
                return "";
            }
    
            // Otherwise we matched a char. Replace with corresponding tag.
            switch (char) {
                case '{': return "@~lb~@";
                case '}': return "@~rb~@";
                case '"': return "@~qu~@";
                case ':': return "@~cn~@";
                case ',': return "@-cm-@";
            }
        });
    }
    

提交回复
热议问题