如果url不以http或https开头的话,如何替换achor标记中的url?

问题描述 投票:0回答:1

我有此样本内容,我想在该样本内容上运行正则表达式以拉出其href在地址部分中不包含http | https的锚标记,并使用基本URL前缀该URL

我正在尝试使用此正则表达式,但尚未完成。当它们不以http或https开头时,我可以选择锚点。

   content.match(/<a\s[^>]*href\s*=\s*"(?!https?:\/\/)[^"]*"[^>]*>/g)
    .map(function (x, index) {

        x = x.replace(/href="(.*?)"/, function (m, $1) {
            if ($1.startsWith('/')) {
                return 'href="' + channel.link + $1 + '"';
            } else {
                return m;
            }
        });

          console.log(x);

    });

但是实际内容保持不变。如果我输入“ x”,我得到了预期的结果。应该怎么做才能使内容具有更新的数据?

javascript
1个回答
0
投票

仅在浏览器中有效如果您的平台是浏览器,则可以实现此目的,并且不需要正则表达式。

document.querySelector("#update-links-btn")
  .addEventListener("click", () => {
    document.querySelectorAll("a").forEach(a => {
      a.setAttribute("href", a.href);
    })
  });
div {
  display: flex;
  flex-direction: column;
}

a:after {
  content: attr(href);
}
<button id="update-links-btn">click me</button>
<div>
  <a href="test.html"></a>
  <a href="/products/1"></a>
  <a href="products/2"></a>
  <a href="google.com"></a>
  <a href="//fb.com"></a>
  <a href="keep.google.com"></a>
  <a href="https://mail.google.com"></a>
  <a href="http://example.com"></a>
  <a href="https://cheerio.js.org"></a>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.