从字符串中提取所有链接

编程入门 行业动态 更新时间:2024-10-23 15:26:27
本文介绍了从字符串中提取所有链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含页面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)

更多推荐

从字符串中提取所有链接

本文发布于:2023-06-13 17:42:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   链接

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!