Improving regex for parsing YouTube / Vimeo URLs

后端 未结 11 1608
半阙折子戏
半阙折子戏 2020-12-13 20:52

I\'ve made a function (in JavaScript) that takes an URL from either YouTube or Vimeo. It figures out the provider and ID for that particular video (demo: http://jsfiddle.net

11条回答
  •  清歌不尽
    2020-12-13 21:13

    For Vimeo, Don't rely on Regex as Vimeo tends to change/update their URL pattern every now and then. As of October 2nd, 2017, there are in total of six URL schemes Vimeo supports.

    https://vimeo.com/*
    https://vimeo.com/*/*/video/*
    https://vimeo.com/album/*/video/*
    https://vimeo.com/channels/*/*
    https://vimeo.com/groups/*/videos/*
    https://vimeo.com/ondemand/*/*
    

    Instead, use their API to validate vimeo URLs. Here is this oEmbed (doc) API which takes an URL, checks its validity and return a object with bunch of video information(check out the dev page). Although not intended but we can easily use this to validate whether a given URL is from Vimeo or not.

    So, with ajax it would look like this,

    var VIMEO_BASE_URL = "https://vimeo.com/api/oembed.json?url=";
    var yourTestUrl = "https://vimeo.com/23374724";
    
    
    $.ajax({
      url: VIMEO_BASE_URL + yourTestUrl,
      type: 'GET',
      success: function(data) {
        if (data != null && data.video_id > 0)
          // Valid Vimeo url
        else
          // not a valid Vimeo url
      },
      error: function(data) {
        // not a valid Vimeo url
      }
    });
    

提交回复
热议问题