javascript - 在一些链接中找到http协议并将其转换为https
问题描述
在我的小代码中,我正在加载一个更改链接颜色的脚本,但我也想用一些正则表达式替换http
需要的地方,https
但我replace
在 JS 中遇到了函数错误。
JS 的正则表达式只会https://
在字符串以http://
(不区分大小写)开头时替换为,否则按原样返回原始字符串。
到目前为止的代码看起来像在片段中,所有链接的颜色都在变化,但replace
有问题。
请让我知道到目前为止的代码有什么问题。
window.onload = function() {
// alert('Page loaded');
let url = document.querySelectorAll('.page-numbers');
console.log(url);
url.forEach((e) => {
e.style.color = 'red';
console.log(e);
e.replace(/^http:\/\//i, 'https://');
});
};
<div class="pagingSection">
<a href="http://www.example.com" class="page-numbers">Link 1</a>
<a href="https://www.example.com" class="page-numbers">Link 2</a>
<a href="http://www.example.com" class="page-numbers">Link 3</a>
<a href="//www.example.com" class="page-numbers">Link 4</a>
<a href="" class="page-numbers">Link 5</a>
</div>
解决方案
您必须编辑href
链接的属性:
看看这个片段。我只修改了这e.replace
条线。
window.onload = function() {
// alert('Page loaded');
let url = document.querySelectorAll('.page-numbers');
console.log(url);
url.forEach((e) => {
e.style.color = 'red';
console.log(e);
e.href = e.href.replace(/^http:\/\//i, 'https://');
});
};
<div class="pagingSection">
<a href="http://www.example.com" class="page-numbers">Link 1</a>
<a href="https://www.example.com" class="page-numbers">Link 2</a>
<a href="http://www.example.com" class="page-numbers">Link 3</a>
<a href="//www.example.com" class="page-numbers">Link 4</a>
<a href="" class="page-numbers">Link 5</a>
</div>
推荐阅读
- node.js - 如何从不同的文件访问 rascal.js 发布?
- python - 周期性数据的核密度估计
- php - Quickpay API回调:未定义索引:HTTP_QUICKPAY_CHECKSUM_SHA256
- alpine - Alpine 提供哪些版本稳定性保证(如果有)?
- php - 如何将值设置为
- python - 这些 Big-O 符号对于简单的循环函数 (Python) 是否正确?
- php - Laravel 主线程被阻塞
- python - 如何从集合中的(x,y)坐标返回x值
- xamarin - 如何防止 Xamarin Forms webview“网页不可用”页面
- go - 戈朗 | unix.setns(FD,CLONE_NEWNS) 因“无效参数”而失败