views:

296

answers:

3

Hi,

Could anyone point me in the right direction to parse an ID from a Vimeo URL in Javascript?

The URL will be entered by a user so I will need to check that they have entered it in the correct format.

I need the ID so that I can use their simple API to retrieve video data.

Any help appreciated.

+2  A: 

Sure.

You should first check the validity/sanity of the URL with a regex and make sure it matches the pattern you expect. (More about regex'es here)

Next you need that ID number, right? Assuming that it's located within the URL, you can extract that also using a regex (backreference)

It's all just basically string and regex handling.

rlb.usa
I need to read into regex, thanks for the links.
Tom
A: 

update: if you want to check for vimeo url first:

function getVimeoId(url) {
  if(url.toLowerCase().indexOf('vimeo') > 0) {
    var re = new RegExp('/[0-9]+', "g");
    var match = re.exec(url);
    if (match == null) {
       return false;
    } else {
       return match[0].substring(1);
    }
  }
  return false;
}

E.g.

alert( getVimeoId( "http://vimeo.com/11918221") );

displays

11918221
Dan Heberden
+1  A: 

As urls for Vimeo videos are made up by http://vimeo.com/ followed by the numeric id you could do the following

var url = "http://www.vimeo.com/7058755";
var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;

var match = url.match(regExp);

if (match){
    alert("id: " + match[2]);
}else{
    alert("not a vimeo url");
}
Sean Kinsey
and what about "www."?
myfreeweb
www is now allowed too
Sean Kinsey
Thanks this works well for what I want to do.
Tom