Skip to main content
2 of 3
added 318 characters in body
qubyte
  • 17.8k
  • 3
  • 32
  • 32

How about this compact little trick?

var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var stringLength = 5; var randomString = Array.apply(null, new Array(stringLength)).map(function () { return possible[Math.floor(Math.random() * possible.length)]; }).join(''); 

You need the Array.apply there to trick the empty array into being an array of undefineds.

If you're coding for ES2015, then building the array is a little simpler:

const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const stringLength = 5; const randomString = Array.from({ length: stringLength }, () => { return possible[Math.floor(Math.random() * possible.length)]; }).join(''); 
qubyte
  • 17.8k
  • 3
  • 32
  • 32