代码之家  ›  专栏  ›  技术社区  ›  Lee Probert

从javascript中的字符串提取URL

  •  0
  • Lee Probert  · 技术社区  · 6 年前

    我正在从服务中获取原始HTML数据,需要从字符串中提取URL。具体来说,在HTML中有一部分URL字符串存在,它是一个名为“数据URL”的参数。有没有一种方法可以直接提取“数据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 回复  |  直到 6 年前
        1
  •  3
  •   nick zoum    6 年前

    您可以创建一个 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包含此文本 \" ,则regex将失败(尽管您可以只添加该约束)。

    另外,如果需要ES5兼容性,则应使用 getAttribute 结束 dataset . 但这只在使用旧版本的IE(最多11个)时才重要。

        2
  •  2
  •   epascarello    6 年前

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

    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
  •  2
  •   Arthur    6 年前

    只需使用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

        4
  •  0
  •   Alan    6 年前

    也许用

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