Skip to content

Instantly share code, notes, and snippets.

@gucheen
Last active August 25, 2017 02:08
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 gucheen/f6f302f090e7581b2b2cf22faa125a44 to your computer and use it in GitHub Desktop.
Save gucheen/f6f302f090e7581b2b2cf22faa125a44 to your computer and use it in GitHub Desktop.
Generate random string/characters in JavaScript
// dec2hex :: Integer -> String
function dec2hex (dec) {
return ('0' + dec.toString(16)).substr(-2);
}
// generateId :: Integer -> String
function generateId (len = 40) {
const arr = new Uint8Array(len / 2);
window.crypto.getRandomValues(arr);
return Array.from(arr, dec2hex).join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment