Javascript 使用正则表达式进行 jQuery Youtube URL 验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2964678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Youtube URL Validation with regex
提问by Mithun Sreedharan
I know there is plenty of question answered over here https://stackoverflow.com/questions/tagged/youtube+regex, but not able find a question similar to me.
我知道这里有很多问题的答案https://stackoverflow.com/questions/tagged/youtube+regex,但找不到与我类似的问题。
Any body has the JavaScript Regular expression for validating the YouTube VIDEO URL's line below listed. Just want to know where such a URL can be possible
任何正文都有用于验证下面列出的 YouTube 视频 URL 行的 JavaScript 正则表达式。只是想知道哪里可以有这样的 URL
http://www.youtube.com/watch?v=bQVoAWSP7k4
http://www.youtube.com/watch?v=bQVoAWSP7k4&feature=popular
http://www.youtube.com/watch?v=McNqjYiFmyQ&feature=related&bhablah
http://youtube.com/watch?v=bQVoAWSP7k4
-- update 1-- -- update 2--
-- 更新 1-- -- 更新 2--
This one worked almost fine, but failed for the URL http://youtube.com/watch?v=bQVoAWSP7k4
这个几乎可以正常工作,但对于 URL http://youtube.com/watch?v=bQVoAWSP7k4却失败了
var matches = $('#videoUrl').val().match(/http:\/\/(?:www\.)?youtube.*watch\?v=([a-zA-Z0-9\-_]+)/);
if (matches) {
alert('valid');
} else {
alert('Invalid');
}
采纳答案by Amarghosh
^http:\/\/(?:www\.)?youtube.com\/watch\?v=\w+(&\S*)?$
//if v can be anywhere in the query list
^http:\/\/(?:www\.)?youtube.com\/watch\?(?=.*v=\w+)(?:\S+)?$
回答by eyecatchUp
ULTIMATE YOUTUBE REGEX
终极 YouTube 正则表达式
Cherry picking
采摘樱桃
Because the explanation is getting longer and longer, I place the final result at the top. Feel free to copy+paste, and go on your way. For a detailed explanation, read "the full story"below.
因为解释的时间越来越长,我把最后的结果放在最上面。随意复制+粘贴,然后继续。有关详细说明,请阅读下面的“完整故事”。
/**
* JavaScript function to match (and return) the video Id
* of any valid Youtube Url, given as input string.
* @author: Stephan Schmitz <[email protected]>
* @url: https://stackoverflow.com/a/10315969/624466
*/
function ytVidId(url) {
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
return (url.match(p)) ? RegExp. : false;
}
The full story
完整的故事
Amarghosh's regexlooks good, at first sight. But it:
乍一看,Amarghosh 的正则表达式看起来不错。但它:
- doesn't match video id's that include dashes (-),
- doesn't validate the id length (
v=aaandv=aaaaaaaaaaaaaaaaaareturn to be valid), - and doesn't match secured URLs at all (https://youtube.com/watch?valid_params)
- 与包含破折号 (-) 的视频 ID 不匹配,
- 不验证 id 长度(
v=aa并v=aaaaaaaaaaaaaaaaaa返回有效), - 并且根本不匹配安全 URL (http s://youtube.com/watch?valid_params)
To match https, the dash character, and to validate the id length, this was my initial suggestion of a modified version of Amarghosh's regex:
为了匹配 https、破折号字符并验证 id 长度,这是我对 Amarghosh 正则表达式的修改版本的最初建议:
^https?:\/\/(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$
^https?:\/\/(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$
UPDATE 1: URLs versus Strings
更新 1:URL 与字符串
After I posted the above pattern, I was asked: "What if the URLis like this;youtube.com/watch?gl=US&hl=en-US&v=bQVoAWSP7k4"?
在我贴出上述模式后,有人问我:“如果URL是这样的youtube.com/watch?gl=US&hl=en-US&v=bQVoAWSP7k4怎么办;”?
First of, please note that this not a URLat all. RFC compliant URLsmust start with the scheme! ;)
首先,请注意这根本不是URL。符合 RFC 的 URL必须以方案开头!;)
Anyway, to match any kind of stringthat indicates to refer to a YouTube video, I updated my answer to exclude the URL scheme being required. So my second suggestion was as follows:
无论如何,为了匹配任何类型的表示引用 YouTube 视频的字符串,我更新了我的答案以排除所需的 URL 方案。所以我的第二个建议如下:
^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$
^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$
UPDATE 2: The ultimate regex
更新 2:终极正则表达式
Then I was asked to add support for a "special case"; the youtu.beshort urls. Initially I did not add these, since it wasn't specifically part of the question. However I updated my answer now with allpossible "special cases". This means that not only have I added support for youtu.be links, but also the request paths "/v" and "/embed".
然后我被要求添加对“特殊情况”的支持;在youtu.be短网址。最初我没有添加这些,因为它不是问题的具体部分。但是,我现在用所有可能的“特殊情况”更新了我的答案。这意味着我不仅添加了对 youtu.be 链接的支持,还添加了请求路径“/v”和“/embed”。
So, may I introduce: My final and ultimate Youtube regex:
那么,我可以介绍一下:我的最终和最终的 Youtube 正则表达式:
^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$
^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$
What strings are matched?
匹配哪些字符串?
Now this pattern will work for any strings, formatted as follows:
现在这个模式适用于任何字符串,格式如下:
Without scheme and subdomain (Domain: youtu.be, Path: /)
没有方案和子域(域:youtu.be,路径:/)
youtu.be/<video:id>
Without scheme, with subdomain (Domain: youtu.be, Path: /)
没有方案,有子域(域:youtu.be,路径:/)
www.youtu.be/<video:id>
With HTTP scheme, without subdomain (Domain: youtu.be, Path: /)
带HTTP方案,不带子域(域:youtu.be,路径:/)
http://youtu.be/<video:id>
With HTTP scheme and subdomain (Domain: youtu.be, Path: /)
使用 HTTP 方案和子域(域:youtu.be,路径:/)
http://www.youtu.be/<video:id>
With HTTPS scheme, without subdomain (Domain: youtu.be, Path: /)
使用 HTTPS 方案,无子域(域:youtu.be,路径:/)
https://youtu.be/<video:id>
With HTTPS scheme and subdomain (Domain: youtu.be, Path: /)
使用 HTTPS 方案和子域(域:youtu.be,路径:/)
https://www.youtu.be/<video:id>
Without scheme and subdomain (Domain: youtube.com, Path: /embed)
没有方案和子域(域:youtube.com,路径:/embed)
youtube.com/embed/<video:id>
youtube.com/embed/<video:id>&other_params
Without scheme, with subdomain (Domain: youtube.com, Path: /embed)
没有方案,有子域(域:youtube.com,路径:/embed)
www.youtube.com/embed/<video:id>
www.youtube.com/embed/<video:id>&other_params
With HTTP scheme, without subdomain (Domain: youtube.com, Path: /embed)
使用 HTTP 方案,没有子域(域:youtube.com,路径:/embed)
http://youtube.com/embed/<video:id>
http://youtube.com/embed/<video:id>&other_params
With HTTP scheme and subdomain (Domain: youtube.com, Path: /embed)
使用 HTTP 方案和子域(域:youtube.com,路径:/embed)
http://www.youtube.com/embed/<video:id>
http://www.youtube.com/embed/<video:id>&other_params
With HTTPS scheme, without subdomain (Domain: youtube.com, Path: /embed)
使用 HTTPS 方案,没有子域(域:youtube.com,路径:/embed)
https://youtube.com/embed/<video:id>
https://youtube.com/embed/<video:id>&other_params
With HTTPS scheme and subdomain (Domain: youtube.com, Path: /embed)
使用 HTTPS 方案和子域(域:youtube.com,路径:/embed)
https://www.youtube.com/embed/<video:id>
https://www.youtube.com/embed/<video:id>&other_params
Without scheme and subdomain (Domain: youtube.com, Path: /v)
没有方案和子域(域:youtube.com,路径:/v)
youtube.com/v/<video:id>
youtube.com/v/<video:id>&other_params
Without scheme, with subdomain (Domain: youtube.com, Path: /v)
没有方案,有子域(域:youtube.com,路径:/v)
www.youtube.com/v/<video:id>
www.youtube.com/v/<video:id>&other_params
With HTTP scheme, without subdomain (Domain: youtube.com, Path: /v)
使用 HTTP 方案,没有子域(域:youtube.com,路径:/v)
http://youtube.com/v/<video:id>
http://youtube.com/v/<video:id>&other_params
With HTTP scheme and subdomain (Domain: youtube.com, Path: /v)
使用 HTTP 方案和子域(域:youtube.com,路径:/v)
http://www.youtube.com/v/<video:id>
http://www.youtube.com/v/<video:id>&other_params
With HTTPS scheme, without subdomain (Domain: youtube.com, Path: /v)
使用 HTTPS 方案,没有子域(域:youtube.com,路径:/v)
https://youtube.com/v/<video:id>
https://youtube.com/v/<video:id>&other_params
With HTTPS scheme and subdomain (Domain: youtube.com, Path: /v)
使用 HTTPS 方案和子域(域:youtube.com,路径:/v)
https://www.youtube.com/v/<video:id>
https://www.youtube.com/v/<video:id>&other_params
Without scheme and subdomain (Domain: youtube.com, Path: /watch)
没有方案和子域(域:youtube.com,路径:/watch)
youtube.com/watch?v=<video:id>
youtube.com/watch?v=<video:id>&other_params
youtube.com/watch?other_params&v=<video:id>
youtube.com/watch?other_params&v=<video:id>&more_params
Without scheme, with subdomain (Domain: youtube.com, Path: /watch)
没有方案,有子域(域:youtube.com,路径:/watch)
www.youtube.com/watch?v=<video:id>
www.youtube.com/watch?v=<video:id>&other_params
www.youtube.com/watch?other_params&v=<video:id>
www.youtube.com/watch?other_params&v=<video:id>&more_params
With HTTP scheme, without subdomain (Domain: youtube.com, Path: /watch)
使用 HTTP 方案,没有子域(域:youtube.com,路径:/watch)
http://youtube.com/watch?v=<video:id>
http://youtube.com/watch?v=<video:id>&other_params
http://youtube.com/watch?other_params&v=<video:id>
http://youtube.com/watch?other_params&v=<video:id>&more_params
With HTTP scheme and subdomain (Domain: youtube.com, Path: /watch)
使用 HTTP 方案和子域(域:youtube.com,路径:/watch)
http://www.youtube.com/watch?v=<video:id>
http://www.youtube.com/watch?v=<video:id>&other_params
http://www.youtube.com/watch?other_params&v=<video:id>
http://www.youtube.com/watch?other_params&v=<video:id>&more_params
With HTTPS scheme, without subdomain (Domain: youtube.com, Path: /watch)
使用 HTTPS 方案,没有子域(域:youtube.com,路径:/watch)
https://youtube.com/watch?v=<video:id>
https://youtube.com/watch?v=<video:id>&other_params
https://youtube.com/watch?other_params&v=<video:id>
https://youtube.com/watch?other_params&v=<video:id>&more_params
With HTTPS scheme and subdomain (Domain: youtube.com, Path: /watch)
使用 HTTPS 方案和子域(域:youtube.com,路径:/watch)
https://www.youtube.com/watch?v=<video:id>
https://www.youtube.com/watch?v=<video:id>&other_params
https://www.youtube.com/watch?other_params&v=<video:id>
https://www.youtube.com/watch?other_params&v=<video:id>&more_params
FUNCTIONAL USAGE
功能用途
The most easy way to use the pattern, is to wrap it into a function such as this one:
使用该模式的最简单方法是将其包装成一个函数,例如:
/**
* JavaScript function to match (and return) the video Id
* of any valid Youtube Url, given as input string.
* @author: Stephan Schmitz <[email protected]>
* @url: https://stackoverflow.com/a/10315969/624466
*/
function ytVidId(url) {
var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
return (url.match(p)) ? RegExp. : false;
}
// for example snippet only!
document.body.addEventListener('click', function(e) {
if (e.target.className == 'yt-url' && 'undefined' !== e.target.value) {
var ytId = ytVidId(e.target.value);
alert(e.target.value + "\r\nResult: " + (!ytId ? 'false' : ytId));
}
}, false);
<!-- Click the buttons to probe URLs -->
<input type="button" value="https://www.youtube.com/watch?v=p-e2G_VcTms&feature=g-logo&context=G29aead6FOAAAAAAABAA" class="yt-url">
<input type="button" value="https://www.youtube.com/latest" class="yt-url">
If the type of the function's result value must be a boolean value, just replace RegExp.$1by true. That's it.
如果函数结果值的类型必须是布尔值,只需替换RegExp.$1为true。就是这样。
One final note on the video Id length: One asked if the ids have a fixed length of 11 chars? and if it might change in the future?
关于视频 ID 长度的最后一个说明:有人问 id 是否具有 11 个字符的固定长度?如果将来可能会改变?
The best answer to that question is probably also the only "official" statement that I've found hereand which says: "I don't see anywhere in the documentation where we officially commit to a standard length of 11 characters for YouTube video ids. It's one of those things where we have a current implementation, and it may stay that way indefinitely. But we're not offering any official commitment to that, so proceed at your own risk."
该问题的最佳答案可能也是我在这里找到的唯一“官方”声明,其中说:“我在文档中没有看到我们正式承诺 YouTube 视频 ID 的标准长度为 11 个字符的任何地方. 这是我们当前实施的其中一件事,它可能会无限期地保持这种状态。但我们不会对此提供任何官方承诺,因此请自行承担风险。”
回答by safdsas
You can not match the id-part with \w+, as it does not include the dash character (-). [a-zA-Z0-9_-]+ would be something more correct.
您不能将 id-part 与 \w+ 匹配,因为它不包含破折号字符 (-)。[a-zA-Z0-9_-]+ 会更正确。
回答by Blagoj Atanasovski
@eyecatchup ubove has an excelent regex, but with the help of regexper.com i saw that his regex will pass any youtube url where the ?v parameter had a value of any word or - sign repeated 11 times. But youtube specificly restricts the video id to 11 characters so a fix for his regex would be
@eyecatchup ubove 有一个优秀的正则表达式,但在 regexper.com 的帮助下,我看到他的正则表达式将传递任何 youtube url,其中 ?v 参数的值是任何单词或 - 符号重复 11 次。但是 youtube 特别将视频 ID 限制为 11 个字符,因此对他的正则表达式的修复是
/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((.|-){11})(?:\S+)?$/
compare the vizualization of his regex
比较他的正则表达式的可视化
http://www.regexper.com/#/%5E%28?:https?:%5C/%5C/%29?%28?:www%5C.%29?%28?:youtu%5C.be%5C/%7Cyoutube%5C.com%5C/%28?:embed%5C/%7Cv%5C/%7Cwatch%5C?v=%7Cwatch%5C?.%2b&v=%29%29%28%28%5Cw%7C-%29%7B11%7D%29%28?:%5CS%2b%29?$/
and my fix
和我的修复
http://www.regexper.com/#%2F%5E(%3F%3Ahttps%3F%3A%5C%2F%5C%2F)%3F(%3F%3Awww%5C.)%3F(%3F%3Ayoutu%5C.be%5C%2F%7Cyoutube%5C.com%5C%2F(%3F%3Aembed%5C%2F%7Cv%5C%2F%7Cwatch%5C%3Fv%3D%7Cwatch%5C%3F.%2B%26v%3D))((%5Ba-zA-Z0-9%5D%7C-)%7B11%7D)(%3F%3A%5CS%2B)%3F%24%2F
as an edit to the 11 character limit changing in future then the current regex would mean that any word or - would have to be repeated exactly 11 times, to that my fix is
作为对未来 11 个字符限制的编辑,那么当前的正则表达式意味着任何单词或 - 都必须精确重复 11 次,我的修复是
/^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11,})(?:\S+)?$/
回答by Mrskman
Improvement for @eyecatchUp's great regex:
改进@eyecatchUp 的正则表达式:
- Add support for m.youtube.com domain
- Add support for youtube-nocookie.com domain by @Nijikokun
- 添加对 m.youtube.com 域的支持
- 通过@Nijikokun 添加对 youtube-nocookie.com 域的支持
^(?:https?:\/\/)?(?:(?:www|m)\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$
Regexper:
正则表达式:
http://regexper.com/#%5E(%3F%3Ahttps%3F%3A%5C%2F%5C%2F)%3F(%3F%3A(%3F%3Awww%7Cm)%5C.)%3F(%3F%3Ayoutu%5C.be%5C%2F%7Cyoutube(%3F%3A-nocookie)%3F%5C.com%5C%2F(%3F%3Aembed%5C%2F%7Cv%5C%2F%7Cwatch%5C%3Fv%3D%7Cwatch%5C%3F.%2B%26v%3D))((%5Cw%7C-)%7B11%7D)(%3F%3A%5CS%2B)%3F%24
回答by Kirill Artemenko
function get_youtube_video_id_from_url(url){
var code = url.match(/v=([^&#]{5,})/)
return (typeof code[1] == 'string') ? code[1] : false;
}
回答by user1948368
function validYT(url) {
var p = /^(?:https?:\/\/)?(?:www\.)?youtube\.com\/watch\?(?=.*v=((\w|-){11}))(?:\S+)?$/;
return (url.match(p)) ? RegExp. : false;
}

