我想要得到v=id从YouTube的URL与JavaScript(没有jQuery,纯JavaScript)。

YouTube URL格式示例

http://www.youtube.com/watch?v=u8nQa1cJyX8&a=GxdCwVVULXctT2lYDEPllDR0LRTutYfW

http://www.youtube.com/watch?v=u8nQa1cJyX8

或在URL中包含视频ID的任何其他YouTube格式。

这些格式的结果

u8nQa1cJyX8


当前回答

这是一个完全不同的解决方案。

你可以从“https://www.youtube.com/oembed?format=json&url=”请求JSON oEmbed文档。rawurlencode($url),然后thumbnail_url有一个固定的格式,匹配一个PCRE模式,如https://i.ytimg.com/vi/([^/]+),第一组是YouTube ID。

其他回答

function parser(url){
    var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\/)|(\?v=|\&v=))([^#\&\?]*).*/;
    var match = url.match(regExp);
    if (match && match[8].length==11){
            alert('OK');
    }else{
            alert('BAD');
    }
}

测试:

https://www.youtube.com/embed/vDoO_bNw7fc - attention first symbol «v» in «vDoO_bNw7fc»

http://www.youtube.com/user/dreamtheater#p/u/1/oTJRivZTMLs
https://youtu.be/oTJRivZTMLs?list=PLToa5JuFMsXTNkrLJbRlB--76IAOjRM9b
http://www.youtube.com/watch?v=oTJRivZTMLs&feature=youtu.be
https://youtu.be/oTJRivZTMLs
http://youtu.be/oTJRivZTMLs&feature=channel
http://www.youtube.com/ytscreeningroom?v=oTJRivZTMLs
http://www.youtube.com/embed/oTJRivZTMLs?rel=0
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/v/oTJRivZTMLs&feature=channel
http://youtube.com/vi/oTJRivZTMLs&feature=channel
http://youtube.com/?v=oTJRivZTMLs&feature=channel
http://youtube.com/?feature=channel&v=oTJRivZTMLs
http://youtube.com/?vi=oTJRivZTMLs&feature=channel
http://youtube.com/watch?v=oTJRivZTMLs&feature=channel
http://youtube.com/watch?vi=oTJRivZTMLs&feature=channel

简单的正则表达式,如果你有完整的URL,保持简单。

results = url.match("v=([a-zA-Z0-9]+)&?")
videoId = results[1] // watch you need.
/^https?:\/\/(?:(?:youtu\.be\/)|(?:(?:www\.)?youtube\.com\/(?:(?:watch\?(?:[^&]+&)?vi?=)|(?:vi?\/)|(?:shorts\/))))([a-zA-Z0-9_-]{11,})/i

下面是一个优化的正则表达式,它可以找到视频id,并准确地遵循YouTube oEmbed对embed url的定义。您可以在这里看到我与测试url的匹配:https://regex101.com/r/q4mWg1/1

它故意不匹配协议相对url(//而不是https://)和youtu-nocookie.com url,因为这些不在oEmbed定义中,从而降低了性能。

你可以在这里查看oEmbed规范: https://oembed.com/

官方提供商的定义,包括YouTube的定义,在这里:https://oembed.com/providers.json

我发现这在Wordpress网站上非常有用,我需要在帖子内容中匹配oEmbed url。

正如webstrap在评论中提到的:

如果视频以“v”开头,并且它来自youtube .be,它就可以工作 正则表达式包含一个小错误\??v?=?这应该在 注意部分,否则如果id以a开头,您将过滤'v' “v”。这应该能解决问题 / ^。* ((youtu.be \ /) | (v \ /) | (\ w / u \ / \ \ /) |(嵌入\ /)|(看\ ? ? v ?=?))([^#\&\?]*).*/

你可以点击共享按钮并复制缩短URL。 例如: 这个YouTube视频的网址是https://www.youtube.com/watch?v=3R0fzCw3amM 但如果你点击分享按钮并复制缩短URL,你会得到这个https://youtu.be/3R0fzCw3amM