Skip to content

Instantly share code, notes, and snippets.

@aackerman
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save aackerman/e0c6a8139ba0d3308f3c to your computer and use it in GitHub Desktop.

Select an option

Save aackerman/e0c6a8139ba0d3308f3c to your computer and use it in GitHub Desktop.
Generate random string in JavaScript
let defaultWhitelist = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let generateRandomString = (len, whitelist = defaultWhitelist) => {
if (len <= 0) throw new Error('Must use a positive length');
let text = '';
while ( len-- ) {
text += whitelist.charAt(Math.floor(Math.random() * whitelist.length));
}
return text;
}
export default generateRandomString;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment