简体   繁体   中英

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"

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

Find all href with match and replace only last

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM