首页 > 解决方案 > 在一些链接中找到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>

标签: javascripthtmlregexreplace

解决方案


您必须编辑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>


推荐阅读