使用JavaScript获取绝对URL
Dealing with URL formats can be a real nightmare. Think of how just a few characters can effect a URL’s absolute endpoint:
处理URL格式可能是一个真正的噩梦。 考虑几个字符如何影响URL的绝对端点:
starting or not starting with
/
以
/
开头或不以/
开头starting with
//
以
//
开头starting with
?
开始于
?
starting with
#
以
#
开头…and so on
…等等
What if you want an absolute URL though? One that starts with http
or https
? You can use an A
element to get that absolute URL!
如果您想要一个绝对URL,该怎么办? 一个以http
或https
开头的? 您可以使用A
元素获取该绝对URL!
JavaScript (The JavaScript)
I’m going to use a function that returns a function so that only one A
element is ever created:
我将使用一个返回一个函数的函数,以便只创建一个A
元素:
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
};
})();
No matter how you pass in the URL string, the URL will come out absolute. Of course strings like `javascript:;` wont come out any different, but real qualified URLs will come out as absolute!
无论您如何传递URL字符串,URL都是绝对的。 当然,像javascript :;这样的字符串不会有任何不同,但是真正合格的URL绝对是绝对的!
翻译自: https://davidwalsh.name/get-absolute-url
还没有评论,来说两句吧...