This question already has an answer here:
What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
This question already has an answer here:
What's the shortest way (within reason) to generate a random alpha-numeric (uppercase, lowercase, and numbers) string in JavaScript to use as a probably-unique identifier?
One-liner with lodash, for random 20 characters (alphanumeric lowercase):
I think the following is the simplest solution which allows for a given length:
Array(myLength).fill(0).map(x => Math.random().toString(36).charAt(2)).join('')
It depends on the arrow function syntax.
Random Key Generator
keyLength argument is the character length you want for the key
Use md5 library: https://github.com/blueimp/JavaScript-MD5
The shortest way:
md5(Math.random())
If you want to limit the size to 5:
md5(Math.random()).substr(0, 5)
Random character:
Random int:
Put it all together:
Fiddle: http://jsfiddle.net/maniator/QZ9J2/
If you only want to allow specific characters, you could also do it like this:
Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/
Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:
Fiddle: http://jsfiddle.net/wSQBx/2/
Alternatively, to use the base36 method as described below you could do something like this: