How do I get the YouTube video ID from a URL?

前端 未结 30 2845
北恋
北恋 2020-11-22 03:06

I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).

Example YouTube URL formats

http://www.youtube.c

30条回答
  •  独厮守ぢ
    2020-11-22 03:21

    I created a function that tests a users input for Youtube, Soundcloud or Vimeo embed ID's, to be able to create a more continous design with embedded media. This function detects and returns an object withtwo properties: "type" and "id". Type can be either "youtube", "vimeo" or "soundcloud" and the "id" property is the unique media id.

    On the site I use a textarea dump, where the user can paste in any type of link or embed code, including the iFrame-embedding of both vimeo and youtube.

    function testUrlForMedia(pastedData) {
    var success = false;
    var media   = {};
    if (pastedData.match('http://(www.)?youtube|youtu\.be')) {
        if (pastedData.match('embed')) { youtube_id = pastedData.split(/embed\//)[1].split('"')[0]; }
        else { youtube_id = pastedData.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0]; }
        media.type  = "youtube";
        media.id    = youtube_id;
        success = true;
    }
    else if (pastedData.match('http://(player.)?vimeo\.com')) {
        vimeo_id = pastedData.split(/video\/|http:\/\/vimeo\.com\//)[1].split(/[?&]/)[0];
        media.type  = "vimeo";
        media.id    = vimeo_id;
        success = true;
    }
    else if (pastedData.match('http://player\.soundcloud\.com')) {
        soundcloud_url = unescape(pastedData.split(/value="/)[1].split(/["]/)[0]);
        soundcloud_id = soundcloud_url.split(/tracks\//)[1].split(/[&"]/)[0];
        media.type  = "soundcloud";
        media.id    = soundcloud_id;
        success = true;
    }
    if (success) { return media; }
    else { alert("No valid media id detected"); }
    return false;
    }
    

提交回复
热议问题