I am currently working on a project using Angular. The API response I am receiving includes three types of links, which I need to iterate over in an array within the HTML.
case 1: <a class="test" href="https://www.google.com/" target="_blank">click here</a> ,
case 2: 'with only href ------- href="https://www.facebook.com/". ',
case 3: 'Without a tag and href ----- "https://www.google.com/"',
I want to display the href
as a hyperlink in my output, navigating to the correct link. This functionality is achieved using [innerHTML]="result"
successfully for case 1.
However, for cases 2 and 3, the output displays plain text instead of hyperlinks. I have attempted using regular expressions to convert them into links, which works fine when stored in separate variables.
The challenge lies in applying these conditions of regular expressions while iterating over an array. Any suggestions to achieve this functionality are greatly appreciated.
I have updated the code in my stackblitz.
Working stackblitz can be found here:
https://stackblitz.com/edit/angular-ivy-ckabj3?file=src%2Fapp%2Fapp.component.html
API Response: The API may return any number of objects with various conditions, not limited to just the three mentioned below.
apiresponse: any = {
response: [
{
hrefmessages:
'with only href ------- href="https://www.facebook.com/". ',
},
{
hrefmessages: 'Without a tag and href ----- "https://www.google.com/"',
},
{
hrefmessages:
'with both a tag and href ------- <a class="test" href="https://www.google.com/" target="_blank">click here</a>. ',
},
],
};
HTML:
<div *ngFor="let result of hrefArray">
<p
[innerHTML]="result"
></p>
</div>
TS:
withHrefAndWithoutAtag() {
let match = this.withJustHref.match(
/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi
);
console.log('match', match);
let final = this.withJustHref.replace('href=', '');
console.log('final', final);
match.map((url) => {
final = final.replace(
url,
'<a href="' + url + '" target="_BLANK">' + url + '</a>'
);
});
console.log(final);
this.withJustHref = final;
return final;
}