用 Tampermonkey 替换特定格式的 href

Replace a specific format of href with Tampermonkey

案例是我想在特定页面中替换所有具有不同客户端 ID 的链接,例如:

<a href="/clients/725144/detail">Details</a>

为此:

<a href="/clients/725144/status">Details</a>

我已经尝试了很多例子,但现在运气不好。

这是一种方法。

var base = "/clients/725144/detail"

var newBase = ""

if (base.includes("detail")) {
newBase = base.replace("detail", "status");
}

console.log(newBase);

你可以试试这个:

a.setAttribute('href', href.replace(/^(\/clients\/\d+)\/detail$/, '/status'))

您甚至可以将链接标记为您已更新:

a.dataset.hrefAltered = true

const replaceLinks = (pattern, replacement, marker = 'hrefAltered') =>
  document.querySelectorAll('a').forEach(a => {
    const href = a.getAttribute('href');
    if (!a.dataset[marker] && href.match(pattern)) {
      a.setAttribute('href', href.replace(pattern, replacement));
      a.dataset[marker] = true;
      console.log(`UPDATE: href=${a.getAttribute('href')}`);
    }
  });

replaceLinks(/^(\/clients\/\d+)\/detail$/, '/status');
<a href="/clients/1/detail">Details</a>
<a href="/clients/12/detail">Details</a>
<a href="/clients/123/detail">Details</a>
<a href="/clients/1234/detail">Details</a>
<a href="/clients/12345/detail">Details</a>