首页 > 解决方案 > 检查 URL 是否有协议 http(s) 如果没有用 javascript 添加一个

问题描述

例如,我正在尝试检查 URL 是否具有协议

<a id ="link1" href="www.example.com"></a>
<a id="link2" href="http://www.example.com"></a>
<a id="link3" href="https://www.example.com"></a>

我想首先检查 URL 是否有协议,如果 href 不包含我要添加的协议//

因此,例如第一个 url 将是:

<a href="//www.example.com"></a>

这是我的代码

var url = document.getElementById("link1");
for(var i=0; i<url.length; i++) {
  $('#link1').append(urls[i].replace(/\/?(\?|#|$)/, '/$1'));
}
 <a id="link" href="www.example.com" ></a>

有人可以帮我解决这个问题吗?

标签: javascriptjquery

解决方案


看看这个

改变

 hrefAttr = new URL("https://"+hrefAttr)

 hrefAttr = new URL("//"+hrefAttr)

或者

 hrefAttr = new URL(location.protocol+"//"+hrefAttr)

满足你的愿望

$(".link").each(function() {
  let hrefAttr = $(this).attr("href");
  const host = "www.example.com"; // location.host; on your server
  if (hrefAttr != $(this).prop("href")) {
    try {
      url = new URL(hrefAttr)
    }
    catch(e) { 
      if (e.message.toLowerCase().includes("invalid") && 
          hrefAttr.includes(host)) { // test that the page host is not in the URL (handles /page.html for example
        hrefAttr = new URL("https://"+hrefAttr)
        console.log(hrefAttr)
        $(this).prop("href",hrefAttr);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="link" href="www.example.com">Change this</a><br/>
<a class="link" href="/page2.html">Do not change this (page)</a><br/>
<a class="link" href="http://www.example.com">Do not change this full url</a><br/>
<a class="link" href="https://www.example.com">Do not change this full url</a><br/>


推荐阅读