Make sure to search for URLs in an array and loop through them according to specific conditions in Angular

I am currently working on a project using Angular. The API response I am receiving includes three types of links, which I need to iterate over in an array within the 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/"',

I want to display the href as a hyperlink in my output, navigating to the correct link. This functionality is achieved using [innerHTML]="result" successfully for case 1.

However, for cases 2 and 3, the output displays plain text instead of hyperlinks. I have attempted using regular expressions to convert them into links, which works fine when stored in separate variables.

The challenge lies in applying these conditions of regular expressions while iterating over an array. Any suggestions to achieve this functionality are greatly appreciated.

I have updated the code in my stackblitz.

Working stackblitz can be found here:

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

API Response: The API may return any number of objects with various conditions, not limited to just the three mentioned below.

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;
  }

Answer №1

The primary adjustment was to modify your functions in a way that they accept a string as input rather than fetching from global variables.

Here is the revised code. Initially, I check the category and then invoke the appropriate mapping method that you have already established.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Make sure to always select the alternative option in ajax

I am trying to create a condition where if the value of id=type_investor is either 1 or 6, an email should be sent using a different controller. Here is my complete code: function (isConfirm) { if (!isConfirm) return; $.ajax({ ...

Redirecting with PHP after registration using AJAX

My registration form incorporates PHP error checking for issues like a short password. AJAX alerts the user with any errors echoed from PHP. Once the if else statement in PHP is executed, the user is successfully registered and redirected to index.php. he ...

Forward ReactJS

https://i.stack.imgur.com/r0IAE.pngI'm having trouble implementing a redirect to a submit confirmation page after pressing the submit button on my form. The backend server is set up to send an email upon submission, but adding an href to the button pr ...

Retrieving Information from Ajax Call Using Python

I am struggling to figure out how to retrieve data from an Ajax request in my JavaScript code within a Python Flask application. The Ajax request I am working with does not involve jQuery. I have attempted using request.form.get() and request.get_json() i ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

Generate and store text inputted from contenteditable

As I embark on creating my own custom rich text editor, I have a couple of questions regarding its functionality. First and foremost, is it possible to prepopulate the text area with content? Additionally, I'm seeking guidance on how to save and utili ...

Utilizing Typescript's optional generic feature to automatically infer the type of the returned object and maintain autocomplete functionality

I have been using TypeScript for some time now and have always faced challenges with this particular issue. My goal is to create an Event system for our application, where I can ensure type safety when creating objects that group events related to a specif ...

Angular Fusion: Delay execution of ngAfterViewInit until data is received from API call in ngOnInit

I'm facing an issue with my code where the API call in ngOnInit is not waiting for the data to be returned before moving on to ngAfterViewInit. I need it to wait because I am performing operations on that data in ngAfterViewInit, but currently, it&apo ...

Interactively retrieving objects from a JavaScript array based on their keys

let arr = [{id:'one',val:1},{id:'two',val:2}] for( let ii of arr ) { if( ii.hasOwnProperty('id') ) arr[ii.id] = ii } This code snippet allows for accessing the elements in the array by their 'id' key. For exampl ...

The functionality of jhtmlarea is not functioning properly when placed within an update

Within my form, I have a jhtmlarea textarea element: textarea id="txtDigital" name="txtDigital" class="form-control" style="background-color:white; resize: vertical !important; " rows="20" placeholder="Details" ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

Having trouble getting the reset select function to work

I'm in the process of developing a website where I'm facing an issue with resetting my form that is constructed using jQuery Uniform. Despite my efforts, I am unable to successfully reset it. Below is the header code snippet: $j(function() { ...

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

Identify the signature of a callback function during runtime

My goal is to pass different callback functions as arguments and have them called with the proper parameters. Here is a simplified example of how it should work. However, determining if process instanceof ITwo makes no sense and I haven't found an ex ...

Pass the PHP data back to my existing webpage for JavaScript to retrieve

I recently set up a form on my WordPress website for users to submit data. Once the form is submitted, I use AJAX to create a new post without having to reload the page. I now need to figure out how to pass the post ID, a simple integer, back to the page s ...

Upgrading from version 3 to version 5 in d3 does not just update the visualization but also introduces a new one

I attempted to upgrade this d3 visualization from version 3 to version 5, but instead of updating within the existing visualization, it continues to add another visualization below. I included: d3.select(".node").selectAll("*").remove(); d3.select(". ...

NextJS allows for custom styling of Tiktok embeds to create a unique and

Currently, I am in the process of constructing a website that integrates Tiktok oEmbed functionality. Thus far, everything is running smoothly, but I have encountered an issue - how can I customize the styling to make the body background transparent? I ha ...

Transfer information from a Vue function to an external JSON document

I would like to store the data for my Vue project in an external JSON file instead of within the Vue function itself. I attempted to retrieve data from an external file using the code below, but encountered issues, possibly due to a conflict with the "ite ...

Java HTML and JS parser available for free!

Is there a parser available that is compatible with AJAX and allows you to customize the method of connecting (I prefer to use my own method to connect to pages)? ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...