Home > Software design >  How to open multiple links from a single hyperlink from anchor tag string in React?
How to open multiple links from a single hyperlink from anchor tag string in React?

Time:02-15

I have a string that has multiple anchor tags passed to the frontend in ReactJs. This string is given by the service call.

eg: "<a href=\"https://www.google.com\" target=\"_blank\"> National ID </a><a href=\"https://www.yahoo.com\" target=\"_blank\"> National ID </a>"

I want to display National ID once and open both the links on a blank page. I figured it out that by getting the href links, I can create an onclick function that opens both the links.

I wanted to know, how to extract href from the string. Or is there a better way to solve the issue that I have? Thanks in advance for any suggestions and solutions.

CodePudding user response:

Use regex to parse string and extract links, like this one:

const input = '<a href="https://www.google.com" target="_blank"> National ID </a><a href="https://www.yahoo.com" target="_blank"> National ID </a>';
const regex = /href="(\S*)"/g;
const links = Array.from(input.matchAll(regex), m => m[1]);

CodePudding user response:

Updated

So if you have high volume of anchor tags, then you can extract all the href values and add the href values in the array.

Code given below

 

let hrefValues=document.getElementsByTagName('a')

let hrefArray = [];

for (var i = 0; i<hrefValues.length; i  )

{  

    hrefArray.push(hrefValues[i].href);

}

 

console.log(hrefArray);

 
 


 

<a href="https://www.google.com/1" target="_blank">

<a href="https://www.google.com/2" target="_blank">

<a href="https://www.google.com/3" target="_blank">

<a href="https://www.google.com/4" target="_blank">

<a href="https://www.google.com/5" target="_blank">

 

  • Related