问题描述
我正在javascript / jscript中编写一个小的windows脚本,用于查找regexp的匹配项,其中包含通过操作文件获得的字符串。
I am writing a small windows script in javascript/jscript for finding a match for a regexp with a string that i got by manipulating a file.
文件路径可以提供相对或绝对的。如何查找给定路径是绝对/相对的并将其转换为绝对文件操作?
The file path can be provided relative or absolute. How to find whether a given path is absolute/relative and convert it to absolute for file manipulation?
推荐答案
来自MSDN文章:
- 任何格式的UNC名称,始终以两个反斜杠字符(\\)开头。有关详细信息,请参阅下一节。
- 带反斜杠的磁盘指示符,例如C:\或d:\。
- 单个反斜杠,例如\directory或\ file.txt。这也称为绝对路径。
- 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.
所以,严格来说,绝对路径是以单个反斜杠( \
)开头的路径。您可以按如下方式检查此条件:
So, strictly speaking, an absolute path is the one that begins with a single backslash (\
). You can check this condition as follows:
if (/^\\(?!\\)/.test(path)) {
// path is absolute
}
else {
// path isn't absolute
}
但通常通过绝对路径,我们实际上是指完全限定路径。在这种情况下,您需要检查所有三个条件,以区分完整路径和相对路径。例如,您的代码可能如下所示:
But often by an absolute path we actually mean a fully qualified path. In this is the case, you need to check all three conditions in order to distinguish between full and relative paths. For example, your code could look like this:
function pathIsAbsolute(path)
{
if ( /^[A-Za-z]:\\/.test(path) ) return true;
if ( path.indexOf("\\") == 0 ) return true;
return false;
}
或(使用单个正则表达式且可读性稍差):
or (using a single regex and a bit less readable):
function pathIsAbsolute(path)
{
return /^(?:[A-Za-z]:)?\\/.test(path);
}
使用方法:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var full_path = fso.GetAbsolutePathName(path);
这篇关于如何查找给定路径是绝对/相对路径还是将其转换为绝对路径以进行文件操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!