Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda