如何使用Regex和JS检索youtube播放列表id

时间:2013-06-01 01:29:10

标签: javascript regex youtube

我正在尝试从youtube链接中检索播放列表ID,如:

https://www.youtube.com/watch?v=hv_X327YUdI&list=SPGznEl712WelO6ZhS8lc2ssweLuQaCKld

https://www.youtube.com/playlist?list=SPGznEl712WelO6ZhS8lc2ssweLuQaCKld

拒绝不属于youtube的链接。

所以在这种情况下,结果将是:

SPGznEl712WelO6ZhS8lc2ssweLuQaCKld

4 个答案:

答案 0 :(得分:3)

这就是我最终做到的方式:

此函数验证链接来自youtube:

    function youtube_validate(url) {

        var regExp = /^(?:https?:\/\/)?(?:www\.)?youtube\.com(?:\S+)?$/;
        return url.match(regExp)&&url.match(regExp).length>0;

    }

此功能检索播放列表ID

  //get playlist id from url
    function youtube_playlist_parser(url){

        var reg = new RegExp("[&?]list=([a-z0-9_]+)","i");
        var match = reg.exec(url);

        if (match&&match[1].length>0&&youtube_validate(url)){
            return match[1];
        }else{
            return "nope";
        }

    }    

答案 1 :(得分:2)

好的,我想你已经提取了链接:

var link = 'https://www.youtube.com/watch?v=hv_X327YUdI&list=SPGznEl712WelO6ZhS8lc2ssweLuQaCKld';

var reg = new RegExp("[&?]list=([a-z0-9_]+)","i");
var match = reg.exec(link);
alert(match[1]);

解释

[&?]       one of these characters
list=
(          capture group 1
 [A-Za-z0-9_]+  all characters that are in [A-Za-z0-9_], one or more times
)          close capture group 1

答案 2 :(得分:0)

(。??:youtube.com (:\ |&安培;)(?:列表)=)((?!videoseries)[A-ZA-Z0-9 _-]

(组#1)

某些播放列表ID有" - " https://regexr.com/3h5gs NP:

https://www.youtube.com/watch?v=ldY6WNjEmGY&list=RDw9pC-51IQ60&index=6

对不起德语技术:>首先我发现了什么

答案 3 :(得分:0)

从网址获取播放列表ID

function playlist_id(url) {
    var VID_REGEX = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
    var regPlaylist = /[?&]list=([^#\&\?]+)/;
    var match = url.match(regPlaylist);
    return match[1];
}

从播放列表网址获取视频ID

function video_id_from_playlist(url) {
    var VID_REGEX = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/
    var video_id = url.match(VID_REGEX)[2];
    return video_id ;
}

或网址中的视频ID

function get_video_id(url) {
    url = url.split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
    return (url[2] !== undefined) ? url[2].split(/[^0-9a-z_\-]/i)[0] : url[0];
}