如何从 url 获取 youtube 视频 ID [英] how to get youtube video id from url

查看:41
本文介绍了如何从 url 获取 youtube 视频 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查 url 是否是有效的 youtube 视频 URL 并从中获取 youtube 视频 ID,到目前为止我正在使用一个简单的 javascript 拆分功能来实现这一点,但是这与 youtube 一样有一些小缺点有多个网址.

我一直在查看其他 stackoverflow 线程,但是它们都只支持 1 个特定的 URL,这不是我需要的.

我需要匹配所有这些 URL 的内容:

<块引用>

http(s)://www.youtu.be/videoID

http(s)://www.youtube.com/watch?v=videoID

(以及可选的任何其他短网址,脚本会自动检测它是否包含 youtube 视频)

非常感谢浏览器可以快速/高效处理的任何想法!

解决方案

试试这个:

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]);} 别的 {console.log("YouTube 网址无效.");}

见正则表达式:

<预><代码>/(?:https?:/{2})?//可选协议,如果有,必须是 http://或 https://(?:w{3}.)?//可选的子域,如果有,必须是 www.YouTube)?//域.匹配youtu"和可选的be"..(?:com|be)//域名后缀必须是 .com 或 .be(?:/watch?v=|/)([^s&]+)//匹配来自'watch'目录或根目录之后的查询字符串中'v'参数的值,任何非空格值./

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.

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.youtube.com/watch?v=videoID

(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!

解决方案

Try this:

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.");
}

see regex:

/
(?: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.
/

这篇关于如何从 url 获取 youtube 视频 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆