Skip to content

Instantly share code, notes, and snippets.

@mikeflynn
Last active July 10, 2022 23:26
Show Gist options
  • Save mikeflynn/5887186 to your computer and use it in GitHub Desktop.
Save mikeflynn/5887186 to your computer and use it in GitHub Desktop.
Google Script: YouTube Channel Username to Channel ID
function ytChannelId(channelName) {
if(channelName) {
var name = getChannelFromUrl(channelName);
var url = "https://gdata.youtube.com/feeds/api/users/" + name + "?fields=id&alt=json";
var result = UrlFetchApp.fetch(url);
var data = Utilities.jsonParse(result.getContentText())
if(typeof data['entry'] !== 'undefined' && data['entry']['id']['$t'] !== 'undefined') {
var id = "UC" + data['entry']['id']['$t'].split('/').pop();
return id;
}
}
return '';
}
function getChannelFromUrl(url) {
var pattern = new RegExp('^(https?:\/\/)?(www\.)?youtube\.com/(user/)?([a-z\-_0-9]+)/?([\?#]?.*)', 'i');
var matches = url.match(pattern);
if(matches) {
return matches[4];
}
return url;
}
@JohnnyTheTank
Copy link

I've created a online youtube username to channel id converter: http://johnnythetank.github.io/youtube-channel-name-converter/

@devhitech
Copy link

const pattern = //i; might be better for added performance, also there are some unescaped slashes in the pattern.

Here I've written a slightly different RegEx for both channel username and ID: https://regex101.com/library/5TBgN1

@flvyu
Copy link

flvyu commented Jun 10, 2017

Is there a channel ID to username version?

@callllum
Copy link

@JohnnyTheTank cool script. Could it have multiple channels in a list and return the ids?

@JohnnyTheTank
Copy link

Good Job @daniel-barrows

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment