coiso
coiso

Reputation: 7479

How to retrieve a youtube playlist id using Regex and JS

I'm trying to retrieve playlist ids from youtube links like:

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

or

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

And to reject links not belonging to youtube.

So in this case the outcome would be:

SPGznEl712WelO6ZhS8lc2ssweLuQaCKld

Upvotes: 0

Views: 2621

Answers (4)

Abdo-Host
Abdo-Host

Reputation: 4103

get playlist id from url

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];
}

get video id from playlist url

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 ;
}

or video id from url

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];
}

Upvotes: 2

Prometeusz M8
Prometeusz M8

Reputation: 1

(?:youtube.com.(?:\?|&)(?:list)=)((?!videoseries)[a-zA-Z0-9_-])

(group #1)

Some playlist id's have "-" https://regexr.com/3h5gs np:

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

Sorry for German techno :> first what i found

Upvotes: 0

coiso
coiso

Reputation: 7479

This is how I ended up doing it:

This function validates that the link is from youtube:

    function youtube_validate(url) {

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

    }

This function retrieves the playlist 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";
        }

    }    

Upvotes: 3

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Ok, i suppose you have already extracted the links:

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]);

explanation

[&?]       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

Upvotes: 2

Related Questions