0

我正在尝试使用以下 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. 用一个替换多个出现的"\"

它完成了工作,但我想知道是否有更好的方法(有解释)

4

2 回答 2

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

参考 :

于 2013-09-18T17:16:47.707 回答
0

单个正则表达式

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

似乎可以解决问题。

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

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

于 2013-09-18T17:39:32.483 回答