我想要得到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
我想要得到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
当前回答
我把Lasnv的回答简化了一点。
它还修复了WebDeb描述的错误。
下面就是:
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
//error
}
下面是一个regexer链接: http://regexr.com/3dnqv
其他回答
你可以点击共享按钮并复制缩短URL。 例如: 这个YouTube视频的网址是https://www.youtube.com/watch?v=3R0fzCw3amM 但如果你点击分享按钮并复制缩短URL,你会得到这个https://youtu.be/3R0fzCw3amM
试试NPM包youtube-id
测试在不同的网址:
const tested = [
'https://www.youtube.com/watch?v={YOUTUBE_ID}&nohtml5=False',
'https://youtu.be/{YOUTUBE_ID}',
'www.youtube.com/embed/{YOUTUBE_ID}'
// ....
]
我做了一个小函数,从Youtube url中提取视频id,如下所示。
var videoId =函数(url) { Var match = url.match(/v=([0-9a-z_-]{1,20})/i); 返回(match ?匹配['1']:false); }; console.log (videoId (' https://www.youtube.com/watch?v=dQw4w9WgXcQ ')); console.log (videoId (' https://www.youtube.com/watch?t=17s&v=dQw4w9WgXcQ ')); console.log (videoId (' https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=17s '));
这个函数将提取视频id,即使url中有多个参数。
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.