Skip to content

Instantly share code, notes, and snippets.

@jonmunson
Forked from eriwen/relativePath.js
Created November 1, 2013 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonmunson/7264242 to your computer and use it in GitHub Desktop.
Save jonmunson/7264242 to your computer and use it in GitHub Desktop.
/**
* 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"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment