I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9]
.
What\'s the best way to do this with JavaScript?
Generate a secure random alphanumeric Base-62
string:
function generateUID(length)
{
return window.btoa(Array.from(window.crypto.getRandomValues(new Uint8Array(length * 2))).map((b) => String.fromCharCode(b)).join("")).replace(/[+/]/g, "").substring(0, length);
}
console.log(generateUID(22)); // "yFg3Upv2cE9cKOXd7hHwWp"
console.log(generateUID(5)); // "YQGzP"