我想要得到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


当前回答

videoId = videoUrl.split('v=')[1].substring(0,11);

其他回答

Python3版本:

import re

def get_youtube_id(url):
   match = re.match('^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))?\?v?=?(?P<id>\w*).*', url);
   return match.group('id')

如果你想在shell/bash/zsh/fish脚本中包含它,下面是如何做到的:

echo -n "$YOUTUBE_URL" | python -c "import re; import sys; m = re.match('^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))?\?v?=?(?P<id>\w*).*', sys.stdin.read()); sys.stdout.write(m.group('id'))"

例子:

echo -n "https://www.youtube.com/watch/?v=APYVWYHS654" | python -c "import re; import sys; m = re.match('^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))?\?v?=?(?P<id>\w*).*', sys.stdin.read()); sys.stdout.write(m.group('id'))"  
APYVWYHS654

由于YouTube视频id被设置为11个字符,我们可以简单地在用v=分割url后使用子字符串。 那么我们就不依赖于最后的&号了。

var sampleUrl = "http://www.youtube.com/watch?v=JcjoGn6FLwI&asdasd";

var video_id = sampleUrl.split("v=")[1].substring(0, 11)

很好很简单:)

我喜欢Surya的回答。只是一个行不通的案例……

String regExp = "/.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";

并不适用于

youtu.be/i4fjHzCXg6c  and  www.youtu.be/i4fjHzCXg6c

升级版:

String regExp = "/?.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";

适用于所有人。

在Youtube短片链接的支持下,Dipo从上面的回答修改了正则表达式

(?:https?:\/\/)?(?:www\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\/?\?v=|\/embed\/|\/shorts\/|\/)(\w+)

测试链接

https://youtu.be/YOUTUBE_ID?123
https://www.youtube.com/embed/YOUTUBE_ID?123
https://www.youtube.com/watch?v=YOUTUBE_ID?asd

https://youtu.be/YOUTUBE_ID&123
https://www.youtube.com/embed/YOUTUBE_ID&123
https://www.youtube.com/watch?v=YOUTUBE_ID&asd

https://youtu.be/YOUTUBE_ID/123
https://www.youtube.com/embed/YOUTUBE_ID/123
https://www.youtube.com/watch?v=YOUTUBE_ID/asd
https://youtube.com/shorts/YOUTUBE_ID?feature=share

请从这里检查您的测试用例

https://regex101.com/r/BUSmeK/1

稍微严格一点的版本:

^https?://(?:www\.)?youtu(?:\.be|be\.com)/(?:\S+/)?(?:[^\s/]*(?:\?|&)vi?=)?([^#?&]+)

测试:

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