parse youtube input links and get youtube ID using jquery ?
I know lots of people asked this sort of question alot but unfortunetly I couldn't sort out my problem .
I have this code in my textarea editor to input a youtube link :
{name:'youtube', key:'Y', replaceWith:'[youtube][![Youtube video Url]!][/youtube]'},
It will ask for youtube video url in a popup window and after that it will put the url between [youtube] and [/youtube].
I would开发者_运维知识库 like to have a youtube parser added to it then if member puts youtube url , it will parse the url and get the youtube video ID and input it in the text area like this :
[youtube] ID [/youtube]
Thanks in advance for your help .
There is a new shortened URL format for youtube URL's... here's an updated script to accomodate both types.
function getVideoId(url){
if(url.indexOf('?') != -1 ) {
var query = decodeURI(url).split('?')[1];
var params = query.split('&');
for(var i=0,l = params.length;i<l;i++)
if(params[i].indexOf('v=') === 0)
return params[i].replace('v=','');
} else if (url.indexOf('youtu.be') != -1) {
return decodeURI(url).split('youtu.be/')[1];
}
return null;
}
var urlLONG = "http://www.youtube.com/watch?v=UF8uR6Z6KLc&feature=feedlik";
var urlSHORT = "http://youtu.be/UF8uR6Z6KLc";
alert(getVideoId(urlLONG));
alert(getVideoId(urlSHORT));
P.S. I am a flash developer and have only tested this in AS3, but simple stuff like this is identical in both languages. if you want to use it in AS3 just swap the alert() with a trace().
Happy coding!
function getVideoId(url){
if(url.indexOf('?') === -1)
return null;
var query = decodeURI(url).split('?')[1];
var params = query.split('&');
for(var i=0,l = params.length;i<l;i++)
if(params[i].indexOf('v=') === 0)
return params[i].replace('v=','');
return null;
}
var url = "http://www.youtube.com/watch?v=yV3i6OoiR4w&feature=BFa&list=PL4A312BE02BA06BB7&lf=bf_play";
alert(getVideoId(url));
update : another solution is to use regex :
var url = "http://www.youtube.com/watch?v=yV3i6OoiR4w&feature=BFa&list=PL4A312BE02BA06BB7&lf=bf_play";
var videoUrl = url.replace(/^.*?(\?|&)(v=([^&]+)).*$/i,'$3');
function getYoutubeId(str){
if(str.indexOf('youtube.com/') != -1 || str.indexOf('youtu.be/') != -1){
var idStr = str.match(/([\&|\?]v\=|youtu\.be\/)([^\&\/\?]*)/);
if(typeof(idStr[2]) != 'undefined'){
return idStr[2];
};
};
return null;
};
精彩评论