I want to get the v=id
from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).
http://www.youtube.c
One more:
var id = url.match(/(^|=|\/)([0-9A-Za-z_-]{11})(\/|&|$|\?|#)/)[2]
It works with any URL showed in this thread.
It won't work when YouTube addS some other parameter with 11 base64 characters. Till then it is the easy way.
I made a small function to extract the video id out of a Youtube url which can be seen below.
var videoId = function(url) {
var match = url.match(/v=([0-9a-z_-]{1,20})/i);
return (match ? 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'));
This function will extract the video id even if there are multiple parameters in the url.
I liked Surya's answer.. Just a case where it won't work...
String regExp = "/.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";
doesn't work for
youtu.be/i4fjHzCXg6c and www.youtu.be/i4fjHzCXg6c
updated version:
String regExp = "/?.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";
works for all.
/^.*(youtu.be\/|v\/|e\/|u\/\w+\/|embed\/|v=)([^#\&\?]*).*/
Tested on:
Inspired by this other answer.
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');
}
}
For testing:
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
We know these characters "?v=" can never appear more than ones but 'v' can appear somehow in the Id Itself so we use "?v=" as delimiter. See it Working Here
//Get YouTube video Id From Its Url
$('button').bind('click',function(){
var
url='http://www.youtube.com/watch?v=u8nQa1cJyX8',
videoId = url.split('?v='),//Split data to two
YouTubeVideoId=videoId[1];
alert(YouTubeVideoId);return false;
});
<button>Click ToGet VideoId</button>