Skip to content

Instantly share code, notes, and snippets.

@andrewroberts
Last active July 26, 2020 16:01
Show Gist options
  • Save andrewroberts/4c6f78307b9ad2ddbf5329126b3383f0 to your computer and use it in GitHub Desktop.
Save andrewroberts/4c6f78307b9ad2ddbf5329126b3383f0 to your computer and use it in GitHub Desktop.
Generate a random string of length n
function generateRandomString(n) {
var chars = ['a', 'b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
chars.push('A', 'B', 'C', 'D', 'E', 'F','G','H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
var randomString = '';
for (i=0; i < n; i++) {
r = Math.random();
r = r * 61;
r = Math.round(r);
randomString = randomString + chars[r];
}
return randomString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment