I'm working on an angular project, I'm getting 3 types of links as shown below in the response of API and I'm iterating it in the HTML over an array.
case 1: <a class="test" rel='nofollow' href="https://www.google.com/" target="_blank">click here</a> ,
case 2: 'with only rel='nofollow' href ------- rel='nofollow' href="https://www.facebook.com/". ',
case 3: 'Without a tag and rel='nofollow' href ----- "https://www.google.com/"',
I want to show the rel='nofollow' href I'm getting in response as a hyperlink in my output and it should navigate to the appropriate link. For that i used [innerHTML]="result" and it working good for case 1. This happened while going through Angular interview questions.
As of now, it is showing in output as plain text for case 2 and case 3. I used regular expressions to convert them to links. It is working fine if I take them in separate variables.
How to use the conditions of regular expressions which I have already done while iterating over an array.
Please help me achieve this functionality.
I have updated my code in the stackblitz. working stackblitz:
https://stackblitz.com/edit/angular-ivy-ckabj3?file=src%2Fapp%2Fapp.component.html
Response from API:
apiresponse: any = {
response: [
{
rel='nofollow' hrefmessages:
'with only rel='nofollow' href ------- rel='nofollow' href="https://www.facebook.com/". ',
},
{
rel='nofollow' hrefmessages: 'Without a tag and rel='nofollow' href ----- "https://www.google.com/"',
},
{
rel='nofollow' hrefmessages:
'with both a tag and rel='nofollow' href ------- <a class="test" rel='nofollow' href="https://www.google.com/" target="_blank">click here</a>. ',
},
],
};
HTML:
<div *ngFor="let result of rel='nofollow' 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('rel='nofollow' href=', '');
console.log('final', final);
match.map((url) => {
final = final.replace(
url,
'<a rel='nofollow' href="' + url + '" target="_BLANK">' + url + '</a>'
);
});
console.log(final);
this.withJustHref = final;
return final;
}
Thank you @ Keerthana Rajendran