RobbTe
RobbTe

Reputation: 405

Regex > get YouTube Playlist ID?

Hi I am trying to get the playlist ID of a youtube url. The code below is not solid since the id 'PLcfQmtiAG0X-fmM85dPlql5wfYbmFumzQ' will not be extracted properly. It only returns 'PLcfQmtiAG0X'. Can someone help me?

var reg = new RegExp("[&?]list=([a-z0-9_]+)","i");
var url = 'https://www.youtube.com/playlist?list=PLcfQmtiAG0X-fmM85dPlql5wfYbmFumzQ';
var match = reg.exec(url);
return match[1];

Upvotes: 1

Views: 1356

Answers (1)

sniperd
sniperd

Reputation: 5274

I do a fair amount of regex work with URLs. Usually you'll want to use a parser but sometimes that is not an option. So to gather params I like to use a negative character class like this

/[&?]list=([^&]+)/i

The [&?] will mean that you won't match &split=123 since it has to start with a & or ?

The [^&]+ is the real magic, it means capture all the non & which is the value you are going for. If you want to play around, this site is pretty good:

https://regex101.com/

Upvotes: 3

Related Questions