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

5 Answers 5

Reset to default 13

I 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