Created
November 14, 2012 22:45
-
-
Save craiga/4075392 to your computer and use it in GitHub Desktop.
randomstring.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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