Improving regex for parsing YouTube / Vimeo URLs

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

    I had a task to enable adding a dropbox videos. So the same input should take href, check it and transform to the playable link which I can then insert in .

    const getPlayableUrl = (url) => {
        // Check youtube and vimeo
        let firstCheck = url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
    
        if (firstCheck) {
            if (RegExp.$3.indexOf('youtu') > -1) {
                return "//www.youtube.com/embed/" + RegExp.$6;
            } else if (RegExp.$3.indexOf('vimeo') > -1) {
                return 'https://player.vimeo.com/video/' + RegExp.$6
            }
        } else {
            // Check dropbox
            let candidate = ''
            if (url.indexOf('.mp4') !== -1) {
                candidate = url.slice(0, url.indexOf('.mp4') + 4)
            } else if (url.indexOf('.m4v') !== -1) {
                candidate = url.slice(0, url.indexOf('.m4v') + 4)
            } else if (url.indexOf('.webm') !== -1) {
                candidate = url.slice(0, url.indexOf('.webm') + 5)
            }
    
            let secondCheck = candidate.match(/(http:|https:|)\/\/(player.|www.)?(dropbox\.com)\/(s\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*\/)?(.*)/);
            if (secondCheck) {
                return 'https://dropbox.com/' + RegExp.$4 + RegExp.$5 + RegExp.$6 + '?raw=1'
            } else {
                throw Error("Not supported video resource.");
            }
        }
    }
    

提交回复
热议问题