从JavaScript中的字符串提取URL

时间:2019-02-07 14:31:48

标签: javascript string

我正在从服务中获取原始HTML数据,并且需要从字符串中提取URL。具体来说,HTML的一部分中存在URL字符串,它是一个称为“ 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)">'

我只需要删除域并将其存储。

4 个答案:

答案 0 :(得分:3)

您可以使用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包含此文本\",则正则表达式将失败(尽管您可以添加该约束)。

此外,如果您想与ES5兼容,则应使用getAttribute而不是dataset。但这仅在使用旧版本的IE(最多11个)时才重要

答案 1 :(得分:2)

只需使用getAttribute

document.getElementById('tv_web_answer_source').getAttribute('data-url')

更好,请使用dataset(因为您要以data-开头的属性)

document.getElementById('tv_web_answer_source').dataset.url

https://developer.mozilla.org/fr/docs/Web/API/HTMLElement/dataset

答案 2 :(得分:2)

最简单的方法是使用DOM获取信息。将html字符串设置为新元素,选择它,然后使用数据集获取属性值。

var div = document.createElement("div")
div.innerHTML = `<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)"></div>`
var str = div.querySelector('[data-url]').dataset.url
var host = new URL(str).hostname
console.log(host, str)

答案 3 :(得分:0)

也许使用

url = s.split("data-url=|\" ")[1];