Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
Check for URL's in array and iterate based on conditions in angular

I'm working with 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" 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 show the href I'm getting in response as an 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.

As of now it is showing in output as a 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 is:

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

Response from API: There can be any number of objects with any conditions , not just below 3 only.

  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 Respuestas
Responde la pregunta

0

The major change was to make your methods take a string as an input, instead of reading from global variables.

This is the result. Basically I check first the category, then call the right map method you already wrote.

app.component.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;
  }
}

app.component.html

<div  *ngFor="let result of hrefArray">
  <p [innerHTML]="result"></p>
</div>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda