尝试从Vimeo URL解析ID时出现问题

时间:2011-01-31 23:08:07

标签: javascript parsing vimeo

我用来从Vimeo视频中获取ID的代码是:函数

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 +"' ";
  third_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);
    }
  }
}

这就是我使用它的方式:

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);
}

问题是它返回undefined。我该怎么做才能纠正?

1 个答案:

答案 0 :(得分:2)

问题是if(url.toLowerCase().indexOf('vimeo') > 0)如果您的网址为vimeo.com/idnro,则网址中的vimeo索引为0.此外,您可能希望修改自己的正则表达式要re = new RegExp('[0-9]+$')来代替

这样的网址
http://vimeo.com/groups/687/videos/3741327

否则你将匹配687,而不是实际的视频ID。我也强烈推荐FireBug来调试这样的东西。这是一颗宝石。

<强>更新

假设形成错误的URL将进入vimeo_id_extract,这就是我要做的。首先从vimeo_id_extract两次返回一个数字,并检查返回的数字是无效的。如果没有那么一切都应该没问题,否则网址中没有视频ID。

如果您知道视频ID将始终终止字符串,则在正则表达式的末尾添加$符号,以确保提取最后七位数序列。

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);
}