grmnth
grmnth

Reputation: 61

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"

Upvotes: 1

Views: 125

Answers (3)

holydragon
holydragon

Reputation: 6728

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>

Upvotes: 0

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

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

Upvotes: 2

Sergey L
Sergey L

Reputation: 547

Find all href with match and replace only last

Upvotes: 0

Related Questions