【问题标题】:Find http protocol in some links and convert it to https在一些链接中找到http协议并将其转换为https
【发布时间】:2021-02-25 12:00:50
【问题描述】:
在我的小代码中,我正在加载一个更改链接颜色的脚本,但我还想使用一些正则表达式将http 替换为https,但我遇到replace 的错误JS中的函数。
只有当字符串以http://(不区分大小写)开头时,JS 的正则表达式才会替换为https://,否则按原样返回原始字符串。
到目前为止的代码看起来像在 sn-p 中,所有链接的颜色都在变化,但 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>
【问题讨论】:
标签:
javascript
html
regex
replace
【解决方案1】:
在 JS 中,如果你必须编辑 HTML 元素的属性,你应该使用setAttribute。
另外你得到一个错误,因为url变量不是一个字符串数组,它是一个数组HTML元素,所以它没有替换功能,你应该使用e.href来读取url
window.onload = function() {
// alert('Page loaded');
let url = document.querySelectorAll('.page-numbers');
url.forEach((e) => {
e.style.color = 'red';
e.setAttribute('href', e.href.replace(/^http:\/\//i, 'https://'));
console.log(e);
});
};
<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>
【解决方案2】:
您必须编辑链接的href 属性:
看看这个sn-p。我只修改了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>