Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate Random String
function generateRandomString(length) {
var id = "";
for (let i = 0; i < length; i++) {
const r = getRandomNumber();
if (r < 0.5) {
id += getNumberWithinRange(r, 0, 9);
} else {
id += String.fromCharCode(getNumberWithinRange(r, 97, 122));
}
}
return id;
}
function getRandomNumber() {
if (window.crypto && window.crypto.getRandomValues) {
// Divide a random UInt32 by the maximum value (2^32 -1) to get a result between 0 and 1
return window.crypto.getRandomValues(new Uint32Array(1))[0] / 4294967295;
}
return Math.random();
}
function getNumberWithinRange(r, min, max) {
return Math.floor(r * (max - min + 1)) + min;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.