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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Up-to-date version: