我正在尝试使用以下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 \\\\");
}
每个替换都会执行特定部分:
"\ "
替换为"\"
" \"
"\"
替换为一个。它完成了工作,但我想知道是否有更好的方法(有解释)
答案 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")
似乎可以解决问题。
这个想法是一个由空格组成的块后跟一个反斜杠后跟一系列其他反斜杠或空格你只想保留反斜杠。
其他情况是删除初始和结束空格。