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

时间:2017-04-06 17:21:27

标签: javascript dom

In Ruby, it’s simple to do this, but in JavaScript, I’m not sure.

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.

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.

3 个答案:

答案 0 :(得分:1)

如果您的baseURL等于当前页面,请尝试以下操作:

var getAbsoluteUrl = (function() {
    var a;

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

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

在此处找到:https://davidwalsh.name/get-absolute-url

尝试过它,它适用于相对URL和绝对URL(它使它们都是绝对的) - 假设你的basePath实际上是你自己的页面。

答案 1 :(得分:1)

URL constructor采用第二个基本参数,它完全符合您的要求:

&#13;
&#13;
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);
});
&#13;
.as-console-wrapper{min-height:100%}
&#13;
<script src="//rawgit.com/github/url-polyfill/0.5.6/url.js"></script>
&#13;
&#13;
&#13;

网址API适用于all major browsers except IE。如果您需要支持IE,there are polyfills available。 Node.js also has it built inconst { URL } = require('url');)。

答案 2 :(得分:0)

使用此脚本(但是首先针对各种情况进行测试,我只是编写它并且不保证我没有忽略任何情况)。请注意,如果URL的路径指定目录而不是文件,则它始终以import { Subject } from 'rxjs'; colorChanged$ = new Subject<string>(); colorChanged(bgColor) { this.colorChanged$.next(bgColor) } ngOnInit() { this.colorChanged$.subscribe(v => console.log(v)); } 结尾,即使浏览器可能未显示该目录。

/