Search code examples
angularionic-frameworkangular12angular13ionic6

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?


Solution

  • Here's what I came with: https://stackblitz.com/edit/plain-angular6-htjxrv

    I made arrays of end values of the old hrefs and srcs by splitting the original text, then build the arrays of new href and src values by adding your intended paths to the content of old hrefs and srcs arrays. Finally, replaced the old href and src values in the text with elements from the array of new values.

    I'm sure it can be done differently, but I think this is clear enough when you look at the code.