我正在尝试使用以下 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 \\\\");
}
每个替换都执行特定部分:
- 去除前后空格
- 将任何替换
"\ "
为"\"
- 替换任何
" \"
- 用一个替换多个出现的
"\"
。
它完成了工作,但我想知道是否有更好的方法(有解释)