Created
March 25, 2013 12:29
-
-
Save fczbkk/5236793 to your computer and use it in GitHub Desktop.
Generates a random string and returns them or sends it to callback.
Great for generating unique identifiers.
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
/* | |
Has two optional options parameters: | |
- length - 8 characters by default | |
- characters - upper- and lowercase characters and numbers by default | |
*/ | |
function getRandomString(options, callback) { | |
options = options || {}; | |
options.length = options.length || 8; | |
options.characters = options.characters || '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'; | |
callback = callback || function () {}; | |
var result = ''; | |
while (options.length--) { | |
result += options.characters.charAt( | |
Math.floor(Math.random() * options.characters.length) | |
); | |
} | |
callback(result); | |
return result; | |
} | |
// EXAMPLES | |
// default use, e.g. "2a2giHof" | |
getRandomString(); | |
// set length, e.g. "xBh" | |
getRandomString({ | |
length : 3 | |
}); | |
// set length and list of characters to use, e.g. "BAB" | |
getRandomString({ | |
length : 3, | |
characters : 'ABC' | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment