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

如何替换字符串中最后一个href属性的内容?

替换字符串中最后一个href属性内容

原始文本

<a href="http://example.com/test this now">Stuff</a>

More stuff

<a href="http://example.com/more?stuff goes here">more</a>

last thing

<a href="http://example.com/more?lasthing goes here">more</a>

需求

仅替换上述文本中最后一个href属性的内容为http://realreference.com/real?the one to replace,不改动其他href属性。

解决方案

方案1:利用正则正向否定预查

通过正则的正向否定预查(?!.*href="),确保匹配的是最后一个href属性:

const originalStr = `<a href="http://example.com/test this now">Stuff</a>

More stuff

<a href="http://example.com/more?stuff goes here">more</a>

last thing

<a href="http://example.com/more?lasthing goes here">more</a>`;

const replacedStr = originalStr.replace(/href="(.*?)"(?!.*href=")/, `href="http://realreference.com/real?the one to replace"`);

console.log(replacedStr);

方案2:通过replace回调函数判断

在全局匹配的回调里,检查当前匹配位置之后是否还有href属性,以此判断是否为最后一个:

const originalStr = `<a href="http://example.com/test this now">Stuff</a>

More stuff

<a href="http://example.com/more?stuff goes here">more</a>

last thing

<a href="http://example.com/more?lasthing goes here">more</a>`;

const replacedStr = originalStr.replace(/href="(.*?)"/g, (match, _, offset) => {
  // 检查当前匹配的href之后是否还有其他href
  if (originalStr.indexOf('href="', offset + match.length) === -1) {
    return `href="http://realreference.com/real?the one to replace"`;
  }
  return match;
});

console.log(replacedStr);

两种方案都能实现仅替换最后一个href属性的需求,可根据实际场景选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:18:34