2

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

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

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

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

或者,如果有人可以帮助我将链接值与链接名称相同的所有 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
4

1 回答 1

3

最好的方法是让 Hugo 自己制作嵌入代码。如果您愿意,您可以将 HTML 代码直接放在 markdown 文档中,或者为了更容易,您可以使用shortcode。Hugo 甚至有一个内置的 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”选择器调整为仅指向内容区域中的链接而不是整个页面可能是一个好主意。另外,我猜这对于有很多链接的页面可能会很慢;如果是这种情况,您可能需要进行一些性能调整。

于 2017-04-19T02:54:39.090 回答