Skip to content

Instantly share code, notes, and snippets.

@craiga
Created November 14, 2012 22:45
Show Gist options
  • Save craiga/4075392 to your computer and use it in GitHub Desktop.
Save craiga/4075392 to your computer and use it in GitHub Desktop.
randomstring.js
/**
* Generate a random string.
*
* @param alphabet (optional) The alphabet used to generate a random string.
* @param minLength (optional) The minimum length of the string. 10 by default.
* @param maxLength (optional) The maximum length of the string. 20 by default.
*
* @author Craig Anderson <[email protected]>
* @link https://gist.github.com/4075392
*/
function randomString(alphabet, minLength, maxLength) {
if(typeof alphabet == "undefined") {
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
}
if(typeof minLength == "undefined") {
minLength = 10;
}
if(typeof maxLength == "undefined") {
maxLength = 20;
}
var s = "";
var alphabetLength = alphabet.length;
var length = Math.floor((Math.random() * minLength) + (maxLength - minLength));
for(var i = 0; i < length; i++) {
s += alphabet.charAt(Math.floor(Math.random() * alphabetLength));
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment