首页 > 解决方案 > 从 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)">'

我只需要剥离域并存储它。

标签: javascriptstring

解决方案


您可以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 兼容性,你应该使用getAttributeover dataset。但这仅在使用旧版本的 IE(最多 11 个)时才重要


推荐阅读