javascript - 从 JavaScript 中的字符串中提取 URL
问题描述
我从服务中获取原始 HTML 数据,并且需要从字符串中提取 URL。具体来说,存在 URL 字符串的 HTML 部分,它是一个名为“data-url”的参数。有没有一种方法可以只提取紧跟在“data-url”之后的 URL。这是一个例子:
let html_str = '<div class="tv-focusable" id="tv_web_answer_source" tabindex="-1" data-url="https://apple.stackexchange.com/questions/323174/does-the-iphone-8-have-any-sort-of-water-resistance-or-waterproof-manufacturing" onclick="onUrlClick(this)">'
我只需要剥离域并存储它。
解决方案
您可以URL
使用new URL(text)
并获取该对象的字符串从字符串创建hostname
对象。唯一剩下的就是选择如何从 html 中提取 url。
使用正则表达式
var html = '<div class="tv-focusable" id="tv_web_answer_source" tabindex="-1" data-url="https://apple.stackexchange.com/questions/323174/does-the-iphone-8-have-any-sort-of-water-resistance-or-waterproof-manufacturing" onclick="onUrlClick(this)">';
console.log(new URL(html.match(/data-url="([^"]*)"/)[1]).hostname);
使用 html
var html = '<div class="tv-focusable" id="tv_web_answer_source" tabindex="-1" data-url="https://apple.stackexchange.com/questions/323174/does-the-iphone-8-have-any-sort-of-water-resistance-or-waterproof-manufacturing" onclick="onUrlClick(this)">';
var element = document.createElement("div");
element.innerHTML = html;
var elementWithData = element.querySelector("[data-url]");
if (elementWithData) {
console.log(new URL(elementWithData.getAttribute("data-url")).hostname);
}
我个人会使用 html 解决方案,因为如果(出于未知原因)url 包含此 text \"
,那么正则表达式将失败(尽管您可以添加该约束)。
另外,如果你想要 ES5 兼容性,你应该使用getAttribute
over dataset
。但这仅在使用旧版本的 IE(最多 11 个)时才重要
推荐阅读
- xamarin.forms - Xam 插件:CrossLocalNotifications.Current.Show 在三星 S8 上不起作用(最新更新后)
- haskell - 斐波那契函数的惰性求值
- android - 带有圆角边缘的按钮动态背景颜色
- excel - 如何将范围设置为活动列?
- python - 我正在使用 scapy 来获取探测信息。我是 python 新手,也是 scapy
- spring-mvc - 如何使用 Spring MVC 在单个 Jasper 报告中查看两个不同的 jasper 报告?
- c# - 实体框架,通过防止左外连接排序
- android - 找不到元素“菜单”的声明
- c# - 如何使用数据网格添加某个值来更新数据库?
- mysql - mysql计算前行时间戳差异并按多个对象分组