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

前端 未结 30 2409
北恋
北恋 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:31

    Java Code: (Works for all the URLs:

    1. http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index
    2. http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o
    3. http://youtube.googleapis.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0
    4. http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s
    5. http://www.youtube.com/embed/0zM3nApSvMg?rel=0"
    6. http://www.youtube.com/watch?v=0zM3nApSvMg
    7. http://youtu.be/0zM3nApSvMg
    8. http://www.youtube.com/watch?v=0zM3nApSvMg/
    9. http://www.youtube.com/watch?feature=player_detailpage&v=8UVNT4wvIGY

    )

        String url = "http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index";
    
        String regExp = "/.*(?:youtu.be\\/|v\\/|u/\\w/|embed\\/|watch\\?.*&?v=)";
        Pattern compiledPattern = Pattern.compile(regExp);
        Matcher matcher = compiledPattern.matcher(url);
        if(matcher.find()){
            int start = matcher.end();
            System.out.println("ID : " + url.substring(start, start+11));
    
        }
    

    For DailyMotion:

    String url = "http://www.dailymotion.com/video/x4xvnz_the-funny-crash-compilation_fun";
    
        String regExp = "/video/([^_]+)/?";
        Pattern compiledPattern = Pattern.compile(regExp);
        Matcher matcher = compiledPattern.matcher(url);
        if(matcher.find()){
            String match = matcher.group();
            System.out.println("ID : " + match.substring(match.lastIndexOf("/")+1));
    
        }
    

提交回复
热议问题