简体   繁体   English

在原始JavaScript中,将相对路径+基本URL转换为绝对URL

[英]In vanilla JavaScript, turn relative path + base URL into absolute URL

In Ruby, it's simple to do this, but in JavaScript, I'm not sure. 在Ruby中,这样做很简单,但是在JavaScript中,我不确定。

Given a starting page, such as http://example.org/foo/bar , I want to be able to take any link on the page, which can have any sort of href such as /x.php , ?p=3 , y.html , etc., and turn it into a fully qualified absolute URL, such as (in the last example) http://example.org/foo/y.html . 给定一个起始页面,例如http://example.org/foo/bar ,我希望能够获得页面上的任何链接,该链接可以具有任何种类的href例如/x.php ?p=3y.html等,并将其转换为完全限定的绝对URL,例如(在最后一个示例中) http://example.org/foo/y.html

Is there any sort of simple way to do this? 有什么简单的方法可以做到这一点吗? If it helps, we can assume these paths do live in an actual web page as actual <a href> elements. 如果有帮助,我们可以假定这些路径作为实际的<a href>元素存在于实际的网页中。

If your baseURL is equal to the current page, try this: 如果您的baseURL等于当前页面,请尝试以下操作:

var getAbsoluteUrl = (function() {
    var a;

    return function(url) {
        if(!a) a = document.createElement('a');
        a.href = url;

        return a.href;
    };
})();

Found here: https://davidwalsh.name/get-absolute-url 这里找到: https://davidwalsh.name/get-absolute-url

Tried it and it worked well for relative as well as absolute URLs (it makes them all absolute) - assuming your basePath is actually your own page. 试了一下,效果不错的相对和绝对的URL(这让他们都绝对) - 假设你的基本路径实际上是你自己的网页。

The URL constructor takes a second, base argument, which does exactly what you want: URL构造函数使用第二个基本参数,该参数恰好满足您的要求:

 const base = 'http://example.org/foo/bar'; [ '/x.php', '?p=3', 'y.html' ].forEach(urlPart => { const url = new URL(urlPart, base); console.log(url.href); }); 
 .as-console-wrapper{min-height:100%} 
 <script src="//rawgit.com/github/url-polyfill/0.5.6/url.js"></script> 

The URL API works in all major browsers except IE . URL API可在IE之外的所有主要浏览器中使用 If you need to support IE, there are polyfills available . 如果您需要支持IE, 则可以使用polyfills Node.js also has it built in ( const { URL } = require('url'); ). Node.js 也内置了它const { URL } = require('url'); )。

Use this script (but test it first for the various cases, I just wrote it and wouldn't guarantee I haven't overlooked any case). 使用此脚本(但是首先针对各种情况对其进行测试,我只是编写了该脚本,并且不能保证我不会忽略任何情况)。 Note that if the path of the URL specifies a directory and not a file, it always ends in a / , even though the browser might not show that. 请注意,如果URL的路径指定的是目录而不是文件,则即使浏览器可能没有显示,它也始终以/结尾。

var getAbsoluteURL = function (url, href) {
    var path = url.split(/[#?]/)[0];
    var basePath = path.slice(0, path.lastIndexOf('/'));
    var domain = url.split('/').slice(0,3).join('/');
    var protocol = url.split('/')[0];

    switch (href.charAt(0)) {
        case '/':
        {
            if (href.length > 1 && href.charAt(1) == '/')
                return protocol + href;
            else
                return domain + href;
        }
        case '#':
        case '?':
            return path + href;
        default:
            return basePath + '/' + href;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM