Home > Back-end >  How to replace last href occurrence in a string?
How to replace last href occurrence in a string?

Time:09-02

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"

CodePudding user response:

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

CodePudding user response:

Find all href with match and replace only last

CodePudding user response:

You can use querySelector in order to query the desired element in the DOM. Using :last-of-type will make it select the last element of the type you select. Therefore, with this code in the first line, you will get the last <a>. After you get the element, you can replace its href attribute by using setAttribute.

let last_a = document.querySelector('a:last-of-type');
last_a.setAttribute('href', 'http://realreference.com/real?the one to replace');
console.log(last_a);
<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>

  • Related