Skip to content

Instantly share code, notes, and snippets.

@mgarratt
Last active December 25, 2015 20:59
Show Gist options
  • Save mgarratt/7039681 to your computer and use it in GitHub Desktop.
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
/**
* 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