Search code examples
javascriptregexregexp-replace

How to replace last href occurrence in a string?


The text is something like the following

<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>

I need to replace what's inside the last href ocurrence in the text, with another reference as http://realreference.com/real?the one to replace

I can actually change the href of all ocurrences in the string with the global flag g after the regex /href="(.*?)"/ and a function like the following:

string.replace(/href="(.*?)"/g, () => {
return `href="http://realreference.com/real?the one to replace"`;
})

I would need to only change it in the last href ocurrence of the string, which in this case it's href="http://example.com/more?lasthing goes here"


Solution

  • If you are looking for a pure regex solution, you can use the following to find the last match:

    pattern(?![\s\S]*pattern)
    

    Example: href="(.+?)"(?![\s\S]*href="(.+?)")

    See it yourself: regex101.com