You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS如何筛选指定href属性的a标签并替换为其内部文本

解决方案

你写的现有工具函数核心逻辑不需要大改,直接利用原生CSS属性选择器就能精准匹配目标a标签。

要筛选href属性值以/开头的a标签,直接使用CSS开头匹配属性选择器a[href^="/"]作为selector参数传入即可,这个选择器会原生匹配所有href属性以/开头的锚点元素,完全符合你的筛选需求。

基础调用示例

对应你给出的测试用例,直接这样调用就能得到预期结果:

const testText = 'lorem ipsum <a href="/s/about">About us</a> lorem ipsum';
const processedText = replaceAnyQueriedElementByItsText(testText, 'a[href^="/"]');
// processedText 输出结果为:lorem ipsum About us lorem ipsum

边界场景优化

如果需要排除//开头的协议相对链接(比如href="//third-party.com"这类虽然以/开头但不属于站内相对路径的链接),可以给匹配逻辑加一层校验,避免误替换:

function replaceRelativeAnchorByText(markup) {
  const doc = new DOMParser().parseFromString(markup, "text/html");

  doc.body.querySelectorAll('a[href^="/"]').forEach(node => {
    const hrefVal = node.getAttribute("href");
    // 仅替换单/开头的站内相对路径链接,跳过//开头的协议相对链接
    if (!hrefVal.startsWith("//")) {
      node.parentNode.replaceChild(document.createTextNode(node.text), node);
    }
  });

  return doc.body.innerHTML;
}

内容的提问来源于stack exchange,提问作者Felix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 04:15:55