【问题标题】:Extract URL from a string of html elements in javascript从javascript中的一串html元素中提取URL
【发布时间】:2021-07-02 18:57:08
【问题描述】:

我在数据中有这个 字符串 元素:

"<html>
  <head>
   <meta http-equiv="pr" content="no-cache">
   <title>Redirection to 20331...</title>
  </head>
  <body>
   <script> language="javascript">
    location = 'https://cloud.analytics.google.com:92/force/ForceRedirect/Redirect.do?id=20331';
   </script>
  </body>
</html>"

我需要提取此字符串中的 URL。

当前实现:

data.split(' ')[6].split("'")[0];

这个 workaround 将链接返回给我并且工作正常,但是因为我基本上是硬编码 URL 的位置,所以我需要一种方法来处理这个问题。感谢任何反馈!

【问题讨论】:

    标签: javascript regex string url ecmascript-6


    【解决方案1】:

    您可以使用正则表达式!例如,我在 HTML 中看到 URL 可以以 location = '...' 的格式出现,因此我们可以将其与正则表达式匹配:

    const match = data.match(/location = '(.+)'/);
    const url = match ? match[1] : null;
    

    谷歌“正则表达式”,网上有大量学习正则表达式的资源。以下是match 函数的参考:

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match

    【讨论】:

      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 2016-05-17
      • 2012-06-07
      • 1970-01-01
      • 2017-07-03
      • 2013-01-17
      • 1970-01-01
      • 2020-09-04
      相关资源
      最近更新 更多