Last active
December 25, 2015 20:59
-
-
Save mgarratt/7039681 to your computer and use it in GitHub Desktop.
A random string generator, useful for passwords and the like. Created in Node.js, but as far as I can tell with work in browsers as well
This file contains 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
/** | |
* Random String | |
* | |
* Generates a random string of specified length using charSet. | |
* | |
* Optional charSet can either be a RegExp MATCH or String of allowed characters | |
* if not provided then (nearly) all characters on a UK Keyboard will be used. | |
* | |
* @param {Int} len Length of random string | |
* @param {String|RegExp} charSet The character set to use | |
* @returns {string} | |
*/ | |
function randomString(len, charSet) { | |
var randomString = ""; // Initialise | |
var allChars = "abcdefghijklmnopqrstuvwxyz" + // Lowercase | |
"ABCDEFGHIJKLMNOPQURSTUVXYZ" + // Uppercase | |
"0123456789" + // Numeric | |
",.?!'\"(){}[]<>£$€@#%^&\\/*-+=_~`¬| "; // Other Characters | |
// charSet is optional, default to every character | |
if (typeof charSet === "undefined") { | |
charSet = allChars; | |
} | |
// If charSet is regex match from allChars | |
if (charSet instanceof RegExp) { | |
charSet = allChars.match(charSet); | |
} | |
// Create string of provided length with random characters from charSet | |
for (var i=0; i < len; i++) { | |
randomString += charSet[Math.floor((Math.random() * charSet.length))]; | |
} | |
// Return the generated string | |
return randomString; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment