JavaScript won't parse a YouTube URL
I'm trying to make a script that will parse a YouTube URL using RegExp on JavaScript to get the video ID, like 开发者_StackOverflow中文版this:
function youtube_id_extract(url) {
var youtube_id;
youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1");
return youtube_id;
}
But I've tried with this URL: http://www.youtube.com/watch?v=Hb_IXwcwcjg and it won't parse. What is wrong with this RegEx?
It works fine:
> var url = "http://www.youtube.com/watch?v=Hb_IXwcwcjg";
> var youtube_id = url.replace(/^[^v]+v.(.{11}).*/,"$1");
"Hb_IXwcwcjg"
However your regular expression is more complicated then it needs to be. You could try this instead which has the same effect (except that it fails with an error if the string doesn't match, instead of silently returning the same string):
youtube_id = url.match(/\?v=(.*)/)[1];
This is from the official google/youtube docs:
getId : function(url) {
return /https?:\/\/(?:[a-zA_Z]{2,3}.)?(?:youtube\.com\/watch\?)((?:[\w\d\-\_\=]+&(?:amp;)?)*v(?:<[A-Z]+>)?=([0-9a-zA-Z\-\_]+))/i.exec(url)[2];
}
精彩评论