Skip to content

Instantly share code, notes, and snippets.

@sloanlance
Last active February 15, 2018 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sloanlance/0f79fe0322932e7fef293b4dde164442 to your computer and use it in GitHub Desktop.
Save sloanlance/0f79fe0322932e7fef293b4dde164442 to your computer and use it in GitHub Desktop.
JS: pseudorandom alphabetical string
// "Pseudorandom", because it's not guaranteed to be truly random.
// Express a floating point random number as base 26 and remove "0." from the beginning.
// Next, to make it alphabetical, replace digits 0-9 with letters q-z.
// @returns {string} Usually 10 to 13 characters in length
Math.random().toString(26).substring(2).replace(/[0-9]/g, function (c) {return 'qrstuvwxyz'[c]});
// Alternate, non-function versions (which is more efficient?)
Math.random().toString(26).substring(2).split('').map(c => 'qrstuvwxyz'[c] || c).join(''); // split to array, replace, join to string
Math.random().toString(26).substring(2).replace(/[0-9]/g, c => 'qrstuvwxyz'[c]); // examine only characters 0-9
Math.random().toString(26).substring(2).replace(/./g, c => 'qrstuvwxyz'[c] || c); // examine all characters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment