Reputation: 43
How can I create Videos IDs with javascript? I want to make a website that gives user random videos, but at the same time for me, I want to learn what is the YouTube Video ID algorithm
Upvotes: 1
Views: 1012
Reputation: 15026
The process is straight forward when laid out this way:
/
with -
. Replace +
with _
. Delete =
if presentKeep in mind this method will almost always lead to a nonexistent YT video. There's just too many combinations, that YT will never run out. Here's a simple JS implementation:
function yt_rand_id() {
let chars2replace = {'/': '-', '+': '_', '=': ''};
let random_bytes = new Uint8Array(8).map(() => Math.floor(Math.random() * 256))
let base64_hash = btoa(String.fromCharCode.apply(0, random_bytes));
base64_hash = base64_hash.replace(/[/+=]/g, match => chars2replace[match]);
return base64_hash;
}
console.log(yt_rand_id(), yt_rand_id(), yt_rand_id(), yt_rand_id());
Hope this helped someone.
Upvotes: 2