Problems While Trying To Parse The ID From a Vimeo URL
The code that I'm using to get the ID from a Vimeo video is this one:function
function vimeo_embed_format(src, width, height) {
var final_syntax;
var first_part;
var second_part;
var third_part;
first_part = "<iframe src='http://player.vimeo.com/video/" + src + "' ";
second_part = "width='" + width + "' height='" + height +"' ";
t开发者_如何学JAVAhird_part = "frameborder='0'></iframe>";
final_part = first_part + second_part + third_part;
return final_part;
}
vimeo_id_extract(url) {
var re;
var match;
var final_id;
re = new RegExp('/[0-9]+', "g");
match = re.exec(url);
if(url.toLowerCase().indexOf('vimeo') > 0) {
if (match == null) {
return false;
} else {
return match[0].substring(1);
}
}
}
And this is how I use it:
function vimeo_do(video, width, height) {
var make_syntax;
var regexp_url;
regexp_url = /((mailto\:|(news|(ht|f)tp(s?))\:\/\/){1}\S+)/;
if(regexp_url.test(video) == false) {
make_syntax = vimeo_embed_format(vimeo_id_extract(video), width, height);
} else {
make_syntax = vimeo_embed_format(video, width, height);
}
document.writeln(make_syntax);
}
The problem is that it returns me undefined
. What should I do to correct?
The problem is this if(url.toLowerCase().indexOf('vimeo') > 0)
if you're url is vimeo.com/idnro
then the index of vimeo
in the url is 0. Also you'd probably want to modify you're regex to be re = new RegExp('[0-9]+$')
to account for urls like
http://vimeo.com/groups/687/videos/3741327
Otherwise you'll match 687 and not the actual video id. I also highly recommend FireBug for debugging stuff like this. It's a gem.
UPDATE
Assuming an ill formed URL will go into vimeo_id_extract
this is what I would do. Firstly return a number on both occasions from the vimeo_id_extract
and check that the number returned is not invalid. If not then everything should be fine, otherwise there was no video id in the url.
If you know that the video id will always terminate the string then add a $
sign to the end of the regex to make sure that the last seven digit sequence is extracted.
function vimeo_id_extract(url) {
var re;
var match;
re = new RegExp('[0-9]{7}');
match = re.exec(url);
if(match != null) {
return match[0];
}
else {
return -1;
}
}
function vimeo_do(video, width, height) {
var make_syntax;
var regexp_url;
regexp_url = /((mailto\:|(news|(ht|f)tp(s?))\:\/\/){1}\S+)/;
if(regexp_url.test(video) == false) {
vimeo_id = vimeo_id_extract(video)
if vimeo_id != -1 {
make_syntax = vimeo_embed_format(vimeo_id_extract(video), width, height);
}
else {
// there is no video id in the string passed in
}
} else {
make_syntax = vimeo_embed_format(video, width, height);
}
document.writeln(make_syntax);
}
精彩评论