javascript - 检查 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>
有人可以帮我解决这个问题吗?
解决方案
看看这个
改变
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/>
推荐阅读
- apache - httpd 进程总是 256
- sql - SqlCommandBuilder 更新命令正在生成命令但不从 DataGridView 更新数据库
- java - 为什么更快重试会提高我的成功率
- ruby - 如何在请求日志中输出 Hanami::Action::Rack#request_id
- python - 减少轴上的编号和刻度之间的距离
- ggplot2 - facet ggplots 2中选定堆栈条形图的条件标签
- java - PreparedStatement、浮点值和 postgresql
- nlp - NLP - 为文本生成指定自定义词汇/单词列表
- c - 跨头文件共享结构
- python - 在 Bigquery 中使用 Job Config 创建范围分区表