Last active
July 10, 2022 23:26
-
-
Save mikeflynn/5887186 to your computer and use it in GitHub Desktop.
Google Script: YouTube Channel Username to Channel ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
Is there a channel ID to username version?
@JohnnyTheTank cool script. Could it have multiple channels in a list and return the ids?
Up-to-date version:
Good Job @daniel-barrows
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've created a online youtube username to channel id converter: http://johnnythetank.github.io/youtube-channel-name-converter/