I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9]
.
What\'s the best way to do this with JavaScript?
In case anyone is interested in a one-liner (although not formatted as such for your convenience) that allocates the memory at once (but note that for small strings it really does not matter) here is how to do it:
Array.apply(0, Array(5)).map(function() {
return (function(charset){
return charset.charAt(Math.floor(Math.random() * charset.length))
}('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));
}).join('')
You can replace 5
by the length of the string you want. Thanks to @AriyaHidayat in this post for the solution to the map
function not working on the sparse array created by Array(5)
.