Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
Verifique las URL en la matriz e itere según las condiciones en angular

Estoy trabajando con un proyecto angular, obtengo 3 tipos de enlaces como se muestra a continuación en la respuesta de API y lo estoy iterando en el html sobre una matriz.

 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/"',

Quiero mostrar el href que recibo como respuesta como un hipervínculo en mi salida y debería navegar al enlace apropiado. Para eso usé [innerHTML]="result" y funcionó bien para el caso 1.

A partir de ahora, se muestra en la salida como texto sin formato para el caso 2 y el caso 3. Usé expresiones regulares para convertirlas en enlaces. Está funcionando bien si los tomo en variables separadas.

Cómo usar las condiciones de las expresiones regulares que ya he hecho al iterar sobre una matriz.

Por favor, ayúdame a lograr esta funcionalidad.

He actualizado mi código en el stackblitz .

Stackblitz de trabajo es:

https://stackblitz.com/edit/angular-ivy-ckabj3?file=src%2Fapp%2Fapp.component.html

Respuesta de la API: puede haber cualquier cantidad de objetos con cualquier condición, no solo por debajo de 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; }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El cambio principal fue hacer que sus métodos tomen una cadena como entrada, en lugar de leer variables globales.

Este es el resultado. Básicamente, verifico primero la categoría, luego llamo al método de mapa correcto que ya escribiste.

aplicación.componente.ts

 import { Component, OnInit } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { hrefArray: any = []; 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>. ', }, ], }; ngOnInit(): void { this.hrefArray = this.mapHrefs(); } mapHrefs(): string[] { return this.apiresponse.response.map((item) => { let message = item.hrefmessages; if (message.includes('<a ')) return message; if (message.includes('href')) return this.withHrefAndWithoutAtag(message); return this.withoutHrefAndAtag(message); }); } withHrefAndWithoutAtag(item: string): string { let match = item.match( /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi ); console.log('match', match); let final = item.replace('href=', ''); console.log('final', final); match.map((url) => { final = final.replace( url, '<a href="' + url + '" target="_BLANK">' + url + '</a>' ); }); console.log(final); return final; } withoutHrefAndAtag(item: string): string { let match = item.match( /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi ); let final = item; match.map((url) => { final = final.replace( url, '<a href="' + url + '" target="_BLANK">' + url + '</a>' ); }); return final; } }

aplicación.componente.html

 <div *ngFor="let result of hrefArray"> <p [innerHTML]="result"></p> </div>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!