Javascript 如何用嵌入替换YouTube视频的超链接URL

Javascript 如何用嵌入替换YouTube视频的超链接URL,javascript,hyperlink,youtube,embed,hugo,Javascript,Hyperlink,Youtube,Embed,Hugo,我正在使用一个静态网站生成器(Hugo),它可以将源代码中的所有纯文本URL转换为指向同一URL的超链接,例如 <p><a href="https://www.youtube.com/watch?v=xLrLlu6KDss">https://www.youtube.com/watch?v=xLrLlu6KDss</a></p> 最好的方法是让Hugo自己制作嵌入代码。如果愿意,您可以将HTML代码直接放在markdown文档中,或者为了更简单,您

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

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

最好的方法是让Hugo自己制作嵌入代码。如果愿意,您可以将HTML代码直接放在markdown文档中,或者为了更简单,您可以使用。雨果甚至有一个好朋友

{{}
如果你把它放在降价文档中,Hugo会在生成页面时嵌入YouTube视频,而不需要任何定制的jQuery代码


编辑:

如果你一定要用JavaScript来做这件事,你可以这样做。(注意:此示例需要jQuery。)

$(“a”)。每个(函数(){
//如果这是错误的URL类型,请快速退出
if(this.protocol!=='http:'&&this.protocol!=='https:'){
返回;
}
//查找YouTube视频的ID
变量id,匹配;
如果(this.hostname=='youtube.com'| | this.hostname=='www.youtube.com'){
//对于URL,如https://www.youtube.com/watch?v=xLrLlu6KDss
matches=this.search.match(/[?&]v=([^&]*)/);
id=匹配项和匹配项[1];
}else if(this.hostname=='youtu.be'){
//对于URL,如https://youtu.be/xLrLlu6KDss
id=this.pathname.substr(1);
}
//检查ID是否只有字母数字字符,以确保
//我们没有引入任何XSS漏洞。
var验证EDID;
如果(id和id.match(/^[a-zA-Z0-9]*$/){
validatedID=id;
}
//添加嵌入的YouTube视频,然后删除链接。
如果(验证EDID){
$(本)
.之前(“”)
.remove();
}
});

这将遍历页面中的所有链接,检查它们是否来自YouTube,找到视频ID,验证ID,然后将链接转换为嵌入式视频。将“a”选择器调整为只指向内容区域中的链接,而不是整个页面,这可能是一个好主意。此外,我猜这可能是缓慢的网页与大量的链接中;如果是这样的话,您可能需要进行一些性能调整。

是的,如果我提前知道YouTube URL,效果会很好。我可能没有完全解释——我正在开发一个系统,将降价内容带入Hugo网站,所以我希望能够动态地自动转换它们。我可能只需要运行一个正则表达式,然后才能将其放入内容中。我已经更新了答案,以包含类似于您需要的jQuery代码。降价是最好的方法,但是jQuery解决方案也应该有效;它确实可以工作,但感觉像是不必要的开销,再加上不得不与未知的视频维度争吵。我现在在我的内容目录上运行两个正则表达式,用hugo短代码替换youtube和vimeo 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
{{< youtube xLrLlu6KDss >}}
$("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();
  }
});