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='http://google.com/'></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.

4

4 回答 4

5

我可能是错的,但我认为您要求的是 a documentFragment,以便您可以href从字符串中提取:

var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>";
var div = document.createElement('div');
div.innerHTML = mylink;
var href = div.firstChild.getAttribute('href');

http://jsfiddle.net/userdude/js8r2/

于 2013-03-27T09:44:37.607 回答
3

如果你可以使用 jQuery,你可以这样做:

var mylink = "<a href='#!takethisout'><img src='http://google.com/'></a>";

var href = $(mylink).attr('href');
alert(href);

示例:http: //jsfiddle.net/pn8M4/

于 2013-03-27T09:49:45.203 回答
2

字符串拆分呢?

var hrefAttr = mylink.split(/href='(.*?)'/)[1]

http://jsfiddle.net/SzHLu/

于 2013-03-27T09:50:39.433 回答
1

您需要正则表达式来解析部分字符串。

mylink.match(/href=["']([^"']+)["']/i)[1];

mylink.split(/href=["']([^"']+)["']/i)[1];

当心 - 它实际上并不解析 html 并寻找 href 属性- 它只会找到匹配正则表达式的字符串。所以在这种情况下

<a href=#!foobar>

不起作用

upd:在不存在匹配的情况下,使用 split 不会破坏代码 - 感谢@freshbm

于 2013-03-27T09:50:02.220 回答