使用JavaScript获取绝对URL

缺乏、安全感 2023-02-22 03:41 83阅读 0赞

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,该怎么办? 一个以httphttps开头的? 您可以使用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元素:

  1. var getAbsoluteUrl = (function() {
  2. var a;
  3. return function(url) {
  4. if(!a) a = document.createElement('a');
  5. a.href = url;
  6. return a.href;
  7. };
  8. })();

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

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读