【发布时间】:2021-12-06 09:24:06
【问题描述】:
我正在处理一个 Angular 项目,我在 API 的响应中获得了 3 种类型的链接,如下所示,我正在 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/"',
我想在我的输出中显示href 作为超链接作为响应,它应该导航到相应的链接。
为此,我使用了[innerHTML]="result",它适用于案例 1。
到目前为止,它在输出中显示为案例 2 和案例 3 的纯文本。 我使用正则表达式将它们转换为链接。 如果我将它们放在单独的变量中,它工作正常。
如何使用我在遍历数组时已经完成的正则表达式的条件。
请帮我实现这个功能。
我在 stackblitz 中更新了我的代码。
工作堆栈闪电战是:
https://stackblitz.com/edit/angular-ivy-ckabj3?file=src%2Fapp%2Fapp.component.html
来自 API 的响应: 可以有任意数量的任意条件的对象,而不仅仅是低于 3 个。
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;
}
【问题讨论】:
标签: javascript arrays angular typescript forms