admin管理员组文章数量:1183725
I have a javascript variable containing the HTML source code of a page (not the source of the current page), I need to extract all links from this variable. Any clues as to what's the best way of doing this?
Is it possible to create a DOM for the HTML in the variable and then walk that?
I have a javascript variable containing the HTML source code of a page (not the source of the current page), I need to extract all links from this variable. Any clues as to what's the best way of doing this?
Is it possible to create a DOM for the HTML in the variable and then walk that?
Share Improve this question edited Sep 28, 2009 at 15:11 Gavin Miller 43.8k22 gold badges126 silver badges191 bronze badges asked Sep 28, 2009 at 15:09 HinchyHinchy 6832 gold badges7 silver badges19 bronze badges 1- I think your best approach will be using some kind of JS HTML document parser. Alternatively you could use regular expressions, but I don't think that's the best way of doing this. – Waleed Amjad Commented Sep 28, 2009 at 15:11
5 Answers
Reset to default 13I don't know if this is the recommended way, but it works: (JavaScript only)
var rawHTML = '<html><body><a href="foo">bar</a><a href="narf">zort</a></body></html>';
var doc = document.createElement("html");
doc.innerHTML = rawHTML;
var links = doc.getElementsByTagName("a")
var urls = [];
for (var i=0; i<links.length; i++) {
urls.push(links[i].getAttribute("href"));
}
alert(urls)
If you're using jQuery, you can really easily I believe:
var doc = $(rawHTML);
var links = $('a', doc);
http://docs.jquery.com/Core/jQuery#htmlownerDocument
This is useful esepcially if you need to replace links...
var linkReg = /(<[Aa]\s(.*)<\/[Aa]>)/g;
var linksInText = text.match(linkReg);
If you're running Firefox YES YOU CAN ! It's called DOMParser , check it out:
DOMParser is mainly useful for applications and extensions based on Mozilla platform. While it's available to web pages, it's not part of any standard and level of support in other browsers is unknown.
If you are running outside a browser context and don't want to pull a HTML parser dependency, here's a naive approach:
var html = `
<html><body>
<a href="https://example.com">Example</a>
<p>text</p>
<a download href='./doc.pdf'>Download</a>
</body></html>`
var anchors = /<a\s[^>]*?href=(["']?)([^\s]+?)\1[^>]*?>/ig;
var links = [];
html.replace(anchors, function (_anchor, _quote, url) {
links.push(url);
});
console.log(links);
本文标签: javascriptExtract all links from a stringStack Overflow
版权声明:本文标题:javascript - Extract all links from a string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738296408a2073400.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论