【问题标题】:Get YouTube ID from youtube embed url [duplicate]从 youtube 嵌入 url 获取 YouTube ID [重复]
【发布时间】:2019-02-20 23:55:05
【问题描述】:

我只想从以下网址获取 youtube id

https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0

 $(".youtube").click(function () {
       console.log(this.href.replace(new RegExp("embed\\/", "i"), 'embed/'));

 });

当用户点击任何链接时,我只想获得 YouTubeID cqyziA30whE,这让我得到了整个网址

【问题讨论】:

  • 我作为一个著名的老问题的骗子结束了这个问题。如果这不能回答您的问题,请相应地进行编辑。

标签: javascript jquery html regex


【解决方案1】:

捕获组中/embed/ 之后的非问号字符,然后使用该捕获的组:

const str = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(
  str.match(/\/embed\/([^?]+)/)[1]
);

您也可以懒惰地重复任何字符,直到出现问号:

const str = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
console.log(
  str.match(/\/embed\/(.+)\?/)[1]
);

【讨论】:

    【解决方案2】:

    您可以使用 RegEx groups 并捕获它。

    var url = 'https://www.youtube.com/embed/nrGk0AuFd_9?controls=1&showinfo=0&rel=0&autoplay=0&loop=0';
    console.log(url.replace(new RegExp("^.*\/embed\/([a-zA-Z0-9_-]+)\?.*", "i"), '$1'));

    【讨论】:

    • 您仅针对基本字符验证它,如果它有其他字符怎么办?例如https://www.youtube.com/watch?v=nrGk0AuFd_9 这有_
    • @Learning 好吧,您可以将字符 -_ 添加到正则表达式中。 YouTube 视频 ID 仅允许使用除 [a-zA-Z0-9] 之外的这些字符。所以最后[a-zA-Z0-9_-]
    【解决方案3】:

    Split() 带有\ 分隔符的字符串,然后split() 带有分隔符? 的结果,所需的结果是拆分数组的第一个元素..

    var string = "https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0";
    var words=string.split('/');
    console.log(words[4].split('?')[0]);

    【讨论】:

    • 这可能会对您有所帮助。 绝不是一个好的答案文本。而是解释你的方法。
    【解决方案4】:

    如果您想要一种避免RegExp 的聪明方法,您可以像这样使用HTMLHyperlinkElementUtils.pathname

    const href = 'https://www.youtube.com/embed/cqyziA30whE?controls=1&showinfo=0&rel=0&autoplay=0&loop=0'
    const a = document.createElement('a')
    
    a.href = href
    
    const id = a.pathname.split('/').pop()
    
    console.log(id)

    根据你的 sn-p,你也许可以做一些简单的事情:

    $(".youtube").click(function() {
      console.log(this.pathname.split('/').pop());
    });
    

    【讨论】:

      猜你喜欢
      • 2012-06-23
      • 1970-01-01
      • 2013-01-19
      • 2023-03-27
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      相关资源
      最近更新 更多