Skip to content

Instantly share code, notes, and snippets.

@zmmbreeze
Created December 2, 2013 11:03
Show Gist options
  • Save zmmbreeze/7747971 to your computer and use it in GitHub Desktop.
Save zmmbreeze/7747971 to your computer and use it in GitHub Desktop.
`path.resolve` for browser
var resolvePath = function () {
function resolve(pathA, pathB) {
// 先做split,得到的结果如下几种
// ‘a’ => ['a']
// 'a/b' => ['a', 'b']
// '/a/b' => ['', 'a', 'b']
// '/a/b/' => ['', 'a', 'b', '']
pathB = pathB.split('/');
if (pathB[0] === '') {
// 如果pathB是想对于根目录
// 则不在考虑pathA,直接返回pathB
return pathB.join('/');
}
pathA = pathA.split('/');
var aLastIndex = pathA.length - 1;
if (pathA[aLastIndex] !== '') {
// 文件名出栈,只保留路径
pathA[aLastIndex] = '';
}
var part;
var i = 0;
while (typeof(part = pathB[i]) === 'string') {
switch (part) {
case '..':
// 进入父级目录
pathA.pop();
pathA.pop();
pathA.push('');
break;
case '.':
// 当前目录
break;
default:
// 进入子目录
pathA.pop();
pathA.push(part);
pathA.push('');
break;
}
i++;
}
return pathA.join('/');
}
var paths = arguments;
var i = 0;
var path;
var r = location.pathname;
var multiSlashReg = /\/\/+/g;
while (typeof(path = paths[i]) === 'string') {
// '//' ==> '/'
path = path.replace(multiSlashReg, '/');
r = resolve(r, path);
i++;
}
return r;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment