I have been trying to take out the href value from a variable which contains a link.
This is my variable which contains a link.
var mylink = "<a href='#!takethisout'><img src='/'></a>"
I tried to get the value #!takethisout , and I also googled it but there are bunch of pages with how to get the href value from a real link.
Is this possible? Thanks.
I have been trying to take out the href value from a variable which contains a link.
This is my variable which contains a link.
var mylink = "<a href='#!takethisout'><img src='http://google./'></a>"
I tried to get the value #!takethisout , and I also googled it but there are bunch of pages with how to get the href value from a real link.
Is this possible? Thanks.
Share Improve this question asked Mar 27, 2013 at 9:39 Navi GamageNavi Gamage 2,7833 gold badges20 silver badges18 bronze badges 1-
1
from mylink variable
mylink.split(/href='(.*?)'/)[1]
– rab Commented Mar 27, 2013 at 9:47
4 Answers
Reset to default 5I could be wrong, but I think you're asking for a documentFragment
so you can extract the href
from the string:
var mylink = "<a href='#!takethisout'><img src='http://google./'></a>";
var div = document.createElement('div');
div.innerHTML = mylink;
var href = div.firstChild.getAttribute('href');
http://jsfiddle/userdude/js8r2/
If you can use jQuery you could do it like this:
var mylink = "<a href='#!takethisout'><img src='http://google./'></a>";
var href = $(mylink).attr('href');
alert(href);
Example: http://jsfiddle/pn8M4/
What about string split?
var hrefAttr = mylink.split(/href='(.*?)'/)[1]
http://jsfiddle/SzHLu/
You need regular expression to parse part string.
mylink.match(/href=["']([^"']+)["']/i)[1];
mylink.split(/href=["']([^"']+)["']/i)[1];
Beware - it doesn't actually parses html and looking for href attribute - it will only find string matching regular expression. so in this case
<a href=#!foobar>
it will NOT work
upd: using split will not break the code in case of non-existent match - thanks @freshbm