如何从网址获取youtube视频ID
我正在尝试检查网址是否是有效的YouTube视频网址并从中获取YouTube视频ID,到目前为止我使用的是简单的javascript拆分功能以实现此目的,但是这有一些小的缺点,因为youtube有多个URL。
I am trying to check whether a url is a valid youtube video URL and get the youtube video ID from it, so far I am using a simple javascript split function in order to achieve this, however this has some minor disadvantages as youtube has multiple URL's.
我一直在查看其他stackoverflow线程,但是它们只支持1个特定的URL,这不是我需要的。
I have been viewing other stackoverflow threads however all of them only support 1 specific URL which is not what I need.
我需要符合所有这些网址的内容:
I need something that matches all these URL's:
http(s)://www.youtu.be / videoID
http(s)://www.youtu.be/videoID
http(s)://www.youtube.com/watch?v = videoID
http(s)://www.youtube.com/watch?v=videoID
(以及脚本自动检测是否包含youtube视频的任何其他短网址)
(and optionally any other short URL's which the script automatically detects whether it contains a youtube video)
任何可以由浏览器快速/高效非常感谢!
Any ideas which can be handled by the browser quick/efficient is greatly appreciated!
试试这个:
var url = "...";
var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
参见正则表达式:
/
(?:https?:\/{2})? // Optional protocol, if have, must be http:// or https://
(?:w{3}\.)? // Optional sub-domain, if have, must be www.
youtu(?:be)? // The domain. Match 'youtu' and optionally 'be'.
\.(?:com|be) // the domain-extension must be .com or .be
(?:\/watch\?v=|\/)([^\s&]+) //match the value of 'v' parameter in querystring from 'watch' directory OR after root directory, any non-space value.
/