Wednesday, May 13, 2009

Validate a youtube link and extract the ID with regular expressions AS3

There's an alternate way here:

// you can just copy paste, I don't feel like colouring all this code :)

// input a youtube link (or embed code)
var youtubeInput:String = "";
// our regular expression to extract the youtube ID
var youtubeIDRX:RegExp = /\?v=(.{11})|\/v\/(.{11})/;
var youtubeFeedURI:String = "";

var youtubeLoader:URLLoader = new URLLoader();
youtubeLoader.addEventListener(Event.COMPLETE, parseYoutubeFeed);
youtubeLoader.addEventListener(IOErrorEvent.IO_ERROR, youtubeFeedERROR);
function parseYoutubeFeed(myEvent:Event):void {
var xml:String =;
if (xml.indexOf("noembed") != -1) {
// looks like embed is turned off, let them know to turn it on
trace("not a tube we can embed.");
} else {
// everything's cool
trace("cool bananas, let's hopscotch!");
function youtubeFeedERROR(e:Event = null):void {
// it might not be a tube if this doesn't load, but they might not have internet either...
trace("not a tube?");

if (youtubeIDRX.test(youtubeInput)) {
var RXresultArray:Array = youtubeIDRX.exec(youtubeInput);
if (!RXresultArray) {
// if there's nothing in the array, they probably didn't give us the right link
trace("not a tube.");
} else if (RXresultArray[1]) {
// if there's something here, it's probably a URL they gave us
youtubeLoader.load(new URLRequest(youtubeFeedURI + RXresultArray[1]));
} else if (RXresultArray[2]) {
// if there's something here, they pasted an embed tag, silly duffers...
youtubeLoader.load(new URLRequest(youtubeFeedURI + RXresultArray[2]));
} else {
// I have no idea how they could get here but anyway, we can't help them...
trace("not a tube?");
} else {
// I don't think it was a youtube link they gave us..
trace("not a tube?");

1 comment:

mark said...

Ta, very handy!