我正在用 javascript/jscript 编写一个小的 Windows 脚本,用于查找正则表达式与我通过操作文件获得的字符串的匹配项。
文件路径可以是相对路径或绝对路径。如何查找给定路径是否为绝对/相对路径并将其转换为绝对路径以进行文件操作?
最佳答案
How to find whether a given path is absolute/relative ...
来自 MSDN 文章 Naming Files, Paths, and Namespaces :
A file name is relative to the current directory if it does not begin with one of the following:
- A UNC name of any format, which always start with two backslash characters ("\\"). For more information, see the next section.
- A disk designator with a backslash, for example "C:\" or "d:\".
- A single backslash, for example, "\directory" or "\file.txt". This is also referred to as an absolute path.
因此,严格来说,绝对路径 是以单个反斜杠 (\
) 开头的路径。您可以按如下方式检查此条件:
if (/^\\(?!\\)/.test(path)) {
// path is absolute
}
else {
// path isn't absolute
}
但通常我们所说的绝对路径实际上是指完全合格的路径。在这种情况下,您需要检查所有三个条件以区分完整路径和相对路径。例如,您的代码可能如下所示:
function pathIsAbsolute(path)
{
if ( /^[A-Za-z]:\\/.test(path) ) return true;
if ( path.indexOf("\\") == 0 ) return true;
return false;
}
或(使用单个正则表达式且可读性稍差):
function pathIsAbsolute(path)
{
return /^(?:[A-Za-z]:)?\\/.test(path);
}
... and convert it to absolute for file manipulation?
使用 FileSystemObject.GetAbsolutePathName
方法:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var full_path = fso.GetAbsolutePathName(path);
关于regex - 如何查找给定路径是否是绝对/相对路径并将其转换为绝对路径以进行文件操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2406739/