Skip to content

Instantly share code, notes, and snippets.

@v19i
Last active March 4, 2021 01:02
Show Gist options
  • Save v19i/411abe971c9c7fe9c79fdc5d4e86a9cf to your computer and use it in GitHub Desktop.
Save v19i/411abe971c9c7fe9c79fdc5d4e86a9cf to your computer and use it in GitHub Desktop.
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