多个正则表达式替换

Ini*_*igo 16 javascript regex

我对正则表达式感到困惑我认为当涉及到这些可怕的代码时我会有阅读障碍..无论如何,必须有一种更简单的方法来做到这一点 - (即在一行中列出一组替换实例),任何人?提前致谢.

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

Mar*_*rot 33

您可以使用功能替换.对于每个匹配,该函数决定应该替换它.

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-@";
        }
    });
}
Run Code Online (Sandbox Code Playgroud)


fif*_*uri 14

您可以定义一个泛型函数,如果您可以在代码的更多部分中重用它,那将是有意义的,从而使其变干.如果你没有理由定义一个通用的,我只会压缩​​清除序列的部分,并保留其他部分替换它们.

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;
}
Run Code Online (Sandbox Code Playgroud)

但是要小心,替换的顺序在这段代码中被改变了.虽然看起来它们可能不会影响结果.