Skip to content

Instantly share code, notes, and snippets.

@yemster
Last active June 26, 2019 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yemster/8270cba4389919a6d3c98ba4a2e99a7e to your computer and use it in GitHub Desktop.
Save yemster/8270cba4389919a6d3c98ba4a2e99a7e to your computer and use it in GitHub Desktop.
Random string generator in Javascript / nonce generator
/*
Generate a random string of a given length.
@params:
length: *required* - length of string to generate
kind: *optional* - character set or sets to use for string generation (default: 'aA#')
Available options
'a' => for lowercase alphabets [a-z]
'A' => for uppercase alphabets [A-Z]
'#' => numbers [0-9]
'!' => special character as defined
'*' => all of the above
Default charset is AlphaNumeric - equivalent to 'aA#'
Typical Usage
console.log(randomString(10)); // alphanumeric strings. Uses 'aA#'
console.log(randomString(10, 'a')); // downcase alpha
console.log(randomString(10, 'A')); // downcase alpha
console.log(randomString(19, '#aA')); // case-insensitive AlphaNumric
console.log(randomString(24, '#A!')); // numbers && upcase alpha && special characters
console.log(randomString(100, '*')); // Everything: case-insensitive AlphaNumric && special characters
*/
var randomString = function(length, kind) {
var i,
str = '',
opts = kind || 'aA#',
possibleChars = '';
if (kind.indexOf('*') > -1) opts = 'aA#!'; // use all possible charsets
// Collate charset to use
if (opts.indexOf('#') > -1) possibleChars += '0123456789';
if (opts.indexOf('a') > -1) possibleChars += 'abcdefghijklmnopqrstuvwxyz';
if (opts.indexOf('A') > -1) possibleChars += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (opts.indexOf('!') > -1) possibleChars += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
for(i = 0; i < length; i++) {
str += possibleChars.charAt(Math.floor(Math.random() * possibleChars.length));
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment