RealSteel
RealSteel

Reputation: 1941

Extract anchor tag href from string javascript/jquery

I've a requirement where I need to extract the 1st href from a string.

Let's say I've a string this way :

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";

Now I need to find all the anchor tags from that string and extract the first anchor tag's href.

I've followed this sample from here and have tried finding the anchor tag from the string.

But I'm unable to get the first element's href.

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";
    var output = LinkString.split(/(?=<a)/)[1];

I've also tried creating a DOM element from the output anchor tag but unable to get the exact href by following the procedure from here

My requirement is to get the Google.com as a final output.

Can anyone help me getting the href?

Upvotes: 1

Views: 4398

Answers (3)

pinturic
pinturic

Reputation: 2263

You can do this way jsfiddle:

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-dec`oration:none; color:#000000;'>URL</a>";

var dom = jQuery.parseHTML("<div>" + LinkString + "</div>");
console.log(dom);
console.log($(dom).find("[href]").attr("href"));

This searches for dom elements that have the href attribute and prints the first href found.

Upvotes: 1

Satpal
Satpal

Reputation: 133453

You can create DOM element then extract the anchor

var LinkString="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";
var firstAnchor = $('<div></div>').append(LinkString).find('a:first');
console.log(firstAnchor.prop('outerHTML')); //Get HTML
console.log(firstAnchor.attr('href')); //Get href attribute
console.log(firstAnchor.prop('href')); //Get href property
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 3

Jai
Jai

Reputation: 74738

You have to use a virtual html element such as div to place the html string value in it then you can target the anchor to extract the href:

var htm="Google Link Is:<a href='www.Google.com' target='_blank' style='text-decoration:none; color:#000000;'>URL</a>";
var href = $('<div>').append(htm).find('a:first').attr('href');
console.log(href)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 4

Related Questions