Skip to content

Instantly share code, notes, and snippets.

@eriwen
Created September 12, 2011 16:11
Show Gist options
  • Save eriwen/1211656 to your computer and use it in GitHub Desktop.
Save eriwen/1211656 to your computer and use it in GitHub Desktop.
Get relative file path in JavaScript
/**
* Given a source directory and a target filename, return the relative
* file path from source to target.
* @param source {String} directory path to start from for traversal
* @param target {String} directory path and filename to seek from source
* @return Relative path (e.g. "../../style.css") as {String}
*/
function getRelativePath(source, target) {
var sep = (source.indexOf("/") !== -1) ? "/" : "\\",
targetArr = target.split(sep),
sourceArr = source.split(sep),
filename = targetArr.pop(),
targetPath = targetArr.join(sep),
relativePath = "";
while (targetPath.indexOf(sourceArr.join(sep)) === -1) {
sourceArr.pop();
relativePath += ".." + sep;
}
var relPathArr = targetArr.slice(sourceArr.length);
relPathArr.length && (relativePath += relPathArr.join(sep) + sep);
return relativePath + filename;
}
console.log(getRelativePath("/users/eric/src/csslint", "/users/eric/style.css"));
@Hocdoc
Copy link

Hocdoc commented Apr 17, 2020

In NodeJS you could use path.relative(from, to)

@lost-scripts
Copy link

Hi. First off, thanks for a so minimalist function! But any clue why if I feed it e.g. like this...

var dirPath = 'file:///D:/Rai/Projects/LS/ls_script/ScriptResources/ls/docs/'
var pagePath = 'file:///D:/Rai/Projects/LS/ls_script/ScriptResources/ls_script/docs/index.html'
const relPath = getRelativePath(dirPath, pagePath);

...it gives me: ../../docs/ when clearly: ../../ls_script/docs/ should be the expected in this case? Sadly I've not enough JS knowledge to can realize where the issue might be and let alone fix it! But hopefully someone has, so there it is and, if so, thanks in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment