有没有办法改进这个Javascript Regex替换

时间:2013-09-18 17:14:20

标签: javascript regex

我正在尝试使用以下Javascript清理Windows文件夹路径。




    function StandardizeFolderPath(inFolderPath) {
        var outFolderPath = inFolderPath.replace(/^\s+|\s+$/g, "");
        outFolderPath = outFolderPath.replace(/\\\s*/g, "\\");
        outFolderPath = outFolderPath.replace(/\s*\\/g, "\\");
        outFolderPath = outFolderPath.replace(/\\{2,}/, "\\");

        alert("^" + inFolderPath + "$           " + "^" + outFolderPath + "$");

        return outFolderPath;
    }

    function Test_StandardizeFolderPath() {
        StandardizeFolderPath("D:\\hel   xo  \\");
        StandardizeFolderPath("D:\\hello  \\        ");
        StandardizeFolderPath("D:\\hello  \\        \\");
        StandardizeFolderPath("D:\\hello  \\        mike \\");
        StandardizeFolderPath("  D:\\hello  \\        jack \\");
        StandardizeFolderPath("  D:\\hello Multiple Slashes \\\\");
    }



每个替换都会执行特定部分:

  1. 从前端和后方删除空格
  2. 将所有"\ "替换为"\"
  3. 替换所有" \"
  4. 将多个"\"替换为一个。
  5. 它完成了工作,但我想知道是否有更好的方法(有解释)

2 个答案:

答案 0 :(得分:2)

您可以合并三个替代品:

function StandardizeFolderPath(inFolderPath) {
    return inFolderPath.replace(/^\s+|\s+$/g, "").replace(/(\s*\\\s*)+/g, "\\");
}

以下是/(\s*\\\s*)+/g的含义:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
/                        start of regex literal
--------------------------------------------------------------------------------
  (                        group \1:
--------------------------------------------------------------------------------
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    \\                       '\'
--------------------------------------------------------------------------------
    \s*                      whitespace (\n, \r, \t, \f, and " ") (0
                             or more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )+                       end of \1 . The + makes it work for one or
                           more occurences
--------------------------------------------------------------------------------
/                         end of regex literal
--------------------------------------------------------------------------------
g                         executes more than once

参考文献:

答案 1 :(得分:0)

单个正则表达式

s.replace(/ *(\\)(\\? *)+|^ *| *$/g, "$1")

似乎可以解决问题。

这个想法是一个由空格组成的块后跟一个反斜杠后跟一系列其他反斜杠或空格你只想保留反斜杠。

其他情况是删除初始和结束空格。