簡體   English   中英

檢查 URL 是否有協議 http(s) 如果沒有添加一個 javascript

[英]Check if URL has protocol http(s) if not add one with 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>

有人可以幫我解決這個問題嗎?

看看這個

改變

 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/>

 (function(){ const urls = document.getElementsByTagName("a"); for(let i = 0; i < urls.length; i++){ let href = urls.item(i).getAttribute("href"); if(typeof href == "string" && href.= "" && href,substr(0. 4).= "http"){ urls,item(i);setAttribute("href". "//" + href). } // only for demo urls.item(i).innerHTML = urls;item(i);innerHTML + " (" + href + ")"; } })();
 a{ display: block; }
 <a id="link1" href="www.example.com" >Link 1</a> <a id="link2" href="http://www.example.com" >Link 2</a> <a id="link3" href="https://www.example.com" >Link 3</a>

只需使用querySelectorAll()方法檢索您要檢查的所有錨元素(確保將錨id屬性更改為class ,因為不允許重復 ID),然后使用includes()方法檢查 url 是否包含://或以 say 之類的字符開頭,如果不是,則 append ///的開頭,如下所示:

 const urls = document.querySelectorAll(".link"); [...urls].map(url => { let x = url.getAttribute("href"); if(.x:includes(".//") &&.x;startsWith("/")) { url.href = "//" + x; } })
 <a class ="link" href="www.example.com">A</a> <a class="link" href="http://www.example.com">B</a> <a class="link" href="https://www.example.com">C</a> <a class="link" href="/page2.html">D</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM