javascript 将绝对路径转换为相对路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12438689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:12:05  来源:igfitidea点击:

Converting an absolute path to a relative path

javascriptnode.js

提问by robdodson

Working in Node I need to convert my request path into a relative path so I can drop it into some templates that have a different folder structure.

在 Node 中工作我需要将我的请求路径转换为相对路径,以便我可以将其放入一些具有不同文件夹结构的模板中。

Basically if I start with the path "/foo/bar" I need my relative path to be ".." If it's "/foo/bar/baz" I need it to be "../.."

基本上如果我从路径“/foo/bar”开始,我需要我的相对路径是“..”如果它是“/foo/bar/baz”我需要它是“../..”

I wrote a pair of functions to do this:

我写了一对函数来做到这一点:

function splitPath(path) {
    return path.split('/').map(dots).slice(2).join('/');
}

function dots() {
    return '..';
}

Not sure if this is the best approach or if it's possible to do it with a regular expression in String.replace somehow?

不确定这是否是最好的方法,或者是否可以在 String.replace 中以某种方式使用正则表达式来实现?

edit

编辑

I should point out this is so I can render everything as static HTML, zip up the whole project, and send it to someone who doesn't have access to a web server. See my first comment.

我应该指出这是这样我可以将所有内容呈现为静态 HTML,压缩整个项目,然后将其发送给无法访问 Web 服务器的人。见我的第一条评论。

回答by Mattias

If I understand you question correct you can use path.relative(from, to)

如果我理解你的问题是正确的,你可以使用 path.relative(from, to)

Documentation

文档

Example:

例子:

var path = require('path');
console.log(path.relative('/foo/bar/baz', '/foo'));

回答by Vadim Baryshev

Node.js have native method for this purposes: path.relative(from, to).

为此,Node.js 有本机方法:path.relative(from, to)

回答by Gung Foo

This might need some tuning but it should work:

这可能需要一些调整,但它应该可以工作:

function getPathRelation(position, basePath, input) {
    var basePathR = basePath.split("/");
    var inputR = input.split("/");
    var output = "";
    for(c=0; c < inputR.length; c++) {
       if(c < position) continue;
       if(basePathR.length <= c) output = "../" + output;
       if(inputR[c] == basePathR[c]) output += inputR[c] + "/";
    }

    return output;
}

var basePath ="/foo"
var position = 2;
var input = "/foo";
console.log(getPathRelation(position,basePath,input));
var input = "/foo/bar";
console.log(getPathRelation(position,basePath,input));
var input = "/foo/bar/baz";
console.log(getPathRelation(position,basePath,input));

Result:

结果:

(an empty string)    
../    
../../