RealSteel RealSteel - 5 months ago 25
jQuery Question

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?

Jai Jai
Answer

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>

Comments