'How to check and rewrite all URLs inside a Typescript String - Angular

I am using Ionic 6 on Angular 13 and I have a json string that has the full text with html codes in it. I need to check the anchor tags and img urls in that string and rewrite the url domain name if required.

For example, I want this fulltext:string variable:

fulltext:string = 
"<p>This is the intro text</p>
<ul>
<li><a href="downloads/category/886-download-pdf">PDF 1 <img src="images/886-download-pdf.jpg" /></a></li>

<li><a href="downloads/category/887-download-pdf">PDF 2 <img src="images/887-download-pdf.jpg" /></a></li>

<li><a href="https://website.com/downloads/category/888-download-pdf">PDF 3 <img src="https://website.com/images/888-download-pdf.jpg" /></a></li>
</ul>"

To become:

"<p>This is the intro text</p>
<ul>
<li><a href="https://website.com/downloads/category/886-download-pdf">PDF 1 <img src="https://website.com/images/886-download-pdf.jpg" /></a></li>

<li><a href="https://website.com/downloads/category/887-download-pdf">PDF 2 <img src="https://website.com/images/887-download-pdf.jpg" /></a></li>

<li><a href="https://website.com/downloads/category/888-download-pdf">PDF 3 <img src="https://website.com/images/888-download-pdf.jpg" /></a></li>
</ul>"

From what I understand so far, I think I need to do the following:

  1. Scan the variable string for all anchor tags and img tags.

  2. See if these urls already has the domain name in it.

  3. If it doesn't, prefix the domain names to these urls.

I tried creating a function in Typescript (or probably better creating a pipe for this), but I am unable to get this done. One of the first hurdle I have is, when I try to get the tags using querySelectorAll or getElementById, it does not work on string. I also tried declaring it as HTMLElement as per some suggestions here and I am unable to proceed through.

Can you kindly help me out here on how this can done in Angular Typescript please?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source