从字符串中提取所有链接 [英] Extract all links from a string
本文介绍了从字符串中提取所有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含页面HTML源代码的JavaScript变量(不是当前页面的源代码),我需要从该变量中提取所有链接。
什么是最好的方式的线索?
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?
可以为变量中的HTML创建一个DOM,然后走吗? / p>
Is it possible to create a DOM for the HTML in the variable and then walk that?
推荐答案
我不知道这是否是推荐的方法,但它有效:(仅限JavaScript)
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)
这篇关于从字符串中提取所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文