最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get href value from a variable - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5

I 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

发布评论

评论列表(0)

  1. 暂无评论