Improving regex for parsing YouTube / Vimeo URLs

后端 未结 11 1560
半阙折子戏
半阙折子戏 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:23

    Regex is wonderfully terse but can quickly get complicated.

    http://jsfiddle.net/8nagx2sk/

    function parseYouTube(str) {
        // link : //youtube.com/watch?v=Bo_deCOd1HU
        // share : //youtu.be/Bo_deCOd1HU
        // embed : //youtube.com/embed/Bo_deCOd1HU
    
        var re = /\/\/(?:www\.)?youtu(?:\.be|be\.com)\/(?:watch\?v=|embed\/)?([a-z0-9_\-]+)/i; 
        var matches = re.exec(str);
        return matches && matches[1];
    }
    
    function parseVimeo(str) {
        // embed & link: http://vimeo.com/86164897
    
        var re = /\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i;
        var matches = re.exec(str);
        return matches && matches[1];
    }
    

    Sometimes simple code is nicer to your fellow developers.

    https://jsfiddle.net/1dzb5ag1/

    // protocol and www neutral
    function getVideoId(url, prefixes) {
      var cleaned = url.replace(/^(https?:)?\/\/(www\.)?/, '');
      for(var i = 0; i < prefixes.length; i++) {
        if (cleaned.indexOf(prefixes[i]) === 0)
          return cleaned.substr(prefixes[i].length)
      }
      return undefined;
    }
    
    function getYouTubeId(url) {
      return getVideoId(url, [
        'youtube.com/watch?v=',
        'youtu.be/',
        'youtube.com/embed/',
        'youtube.googleapis.com/v/'
      ]);
    }
    
    function getVimeoId(url) {
      return getVideoId(url, [
        'vimeo.com/',
        'player.vimeo.com/'
      ]);
    }
    

    Which do you prefer to update?

提交回复
热议问题