如何替换字符串中最后一个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
相关产品推荐
相关产品推荐

