【问题标题】:How to replace hyperlinked URL to YouTube Video with embed如何使用嵌入替换 YouTube 视频的超链接 URL
【发布时间】:2017-09-14 23:57:10
【问题描述】:

我正在使用静态网站生成器 (Hugo),它将源中的所有纯文本 URL 转换为指向同一 URL 的超链接,例如

<p><a href="https://www.youtube.com/watch?v=xLrLlu6KDss">https://www.youtube.com/watch?v=xLrLlu6KDss</a></p>

我宁愿将它作为嵌入式视频。

有很多代码位可以将纯文本 YouTube URL 转换为有效的嵌入 (example),但是当它带有超链接时如何获得嵌入?

或者如果有人可以帮助我将链接值与链接名称相同的所有 href 链接转换为纯 URL?例如如何更换

<p><a href="https://www.youtube.com/watch?v=xLrLlu6KDss">https://www.youtube.com/watch?v=xLrLlu6KDss</a></p>

https://www.youtube.com/watch?v=xLrLlu6KDss

【问题讨论】:

    标签: javascript hyperlink youtube embed hugo


    【解决方案1】:

    最好的方法是让 Hugo 自己制作嵌入代码。如果您愿意,可以将 HTML 代码直接放在 markdown 文档中,或者为了更容易,您可以使用 shortcode。 Hugo 甚至有一个built-in shortcode for YouTube

    {{< youtube xLrLlu6KDss >}}
    

    如果你把它放在你的 Markdown 文档中,Hugo 会在生成页面时嵌入 YouTube 视频,并且不需要任何自定义 jQuery 代码。


    编辑:

    如果您绝对必须使用 JavaScript 执行此操作,您可以执行以下操作。 (注意:此示例需要 jQuery。)

    $("a").each(function () {
      // Exit quickly if this is the wrong type of URL
      if (this.protocol !== 'http:' && this.protocol !== 'https:') {
        return;
      }
    
      // Find the ID of the YouTube video
      var id, matches;
      if (this.hostname === 'youtube.com' || this.hostname === 'www.youtube.com') {
        // For URLs like https://www.youtube.com/watch?v=xLrLlu6KDss
        matches = this.search.match(/[?&]v=([^&]*)/);
        id = matches && matches[1];
      } else if (this.hostname === 'youtu.be') {
        // For URLs like https://youtu.be/xLrLlu6KDss
        id = this.pathname.substr(1);
      }
    
      // Check that the ID only has alphanumeric characters, to make sure that
      // we don't introduce any XSS vulnerabilities.
      var validatedID;
      if (id && id.match(/^[a-zA-Z0-9]*$/)) {
        validatedID = id;
      }
    
      // Add the embedded YouTube video, and remove the link.
      if (validatedID) {
        $(this)
          .before('<iframe width="200" height="100" src="https://www.youtube.com/embed/' + validatedID + '" frameborder="0" allowfullscreen></iframe>')
          .remove();
      }
    });
    

    这会遍历页面中的所有链接,检查它们是否来自 YouTube,找到视频 ID,验证 ID,然后将链接转换为嵌入视频。将“a”选择器定制为仅指向内容区域中的链接而不是整个页面可能是一个好主意。另外,我猜这对于有很多链接的页面可能会很慢;如果是这种情况,您可能需要进行一些性能调整。

    【讨论】:

    • 是的,如果我提前知道 YouTube 网址就可以了。我可能没有解释完整——我正在开发一个将降价内容带入 Hugo 网站的系统,所以我希望能够即时自动转换它们。在将其放入内容之前,我可能只需要运行一个正则表达式。
    • 我已经更新了我的答案以包含类似于您需要的 jQuery 代码。在 markdown 中做是最好的方法,但 jQuery 解决方案也应该可以。
    • 非常感谢;它确实有效,但感觉像是不必要的开销,而且不得不与未知的视频尺寸争吵。我现在在我的内容目录上运行两个正则表达式,用 Hugo 短代码替换 youtube 和 vimeo 网址,这些代码响应迅速
    猜你喜欢
    • 2012-01-15
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2018-01-09
    • 2011-11-19
    • 2011-10-01
    • 2021-04-14
    相关资源
    最近更新 更多