How to find whether a given path is absolute/relative ...
From the MSDN article 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.
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);
}
... and convert it to absolute for file manipulation?
Use the FileSystemObject.GetAbsolutePathName
method:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var full_path = fso.GetAbsolutePathName(path);