我需要基于当前目录构建返回到预定义顶级目录的路径数组。
在Javascript中,有两个变量“ topLevelDirectory”和“ currentDirectory”
我需要之间所有路径的数组。
例如:
topLevelDirectory = "/sectionA/sectionB"
currentDirectory = "/sectionA/sectionB/sectionC/sectionD/sectionE
”
我需要一个具有值的数组“ allPaths”:
allPaths[0] = '/sectionA/sectionB/'
allPaths[1] = '/sectionA/sectionB/sectionC/'
allPaths[2] = '/sectionA/sectionB/sectionC/sectionD/'
allPaths[3] = '/sectionA/sectionB/sectionC/sectionD/sectionE/'
我正在使用Jquery。
我知道我可以拆分currentDirectory,但是那时我没有得到所需的值,
'sectionC'而不是'/ sectionA / sectionB / sectionC /'
我不希望得到完整的代码答案,只是我应该尝试将哪些功能或过程联系在一起的一些帮助。
任何帮助表示赞赏。
最佳答案
这不是很优雅或非常强大,但似乎可以用于您的示例...
function segmentPath(topLevelDir, currentDir) {
function normalizePath(str) {
return str.replace(/(^\/+|\/+$)/g, ''); // strip leading/trailing slashes
}
topLevelDir = normalizePath(topLevelDir);
currentDir = normalizePath(currentDir);
var relativePath = normalizePath(currentDir.slice(topLevelDir.length));
relativePath = relativePath.split('/');
var segments = ["/" + topLevelDir];
for (var i = 0, l = relativePath.length; i < l; i++) {
segments.push(segments[i] + "/" + relativePath[i]);
}
return segments;
}
这是一个演示:http://jsfiddle.net/QrCBn/