I want to generate a random string that has to have 5 letters from a-z and 3 numbers.
How can I do this with JavaScript?
I\'ve got the following script, but
A little more maintainable and secure approach.
An update to expand on what I meant and how it works.
Secure. MDN is pretty explicit about the use of Math.random for anything related to security:
Math.random()does not provide cryptographically secure random numbers. Do not use them for anything related to security. Use the Web Crypto API instead, and more precisely the window.crypto.getRandomValues() method.
Looking at the can-i-use for getRandomValues in 2020 you probably don't need the msCrypto and Math.random fallback any more, unless you care about ancient browsers.
Maintainable is mostly about the RegExp _pattern as an easy way to define what character classes you allow in the password. But also about the 3 things where each does its job: defines a pattern, gets a random byte as securely as possible, provides a public API to combine the two.
var Password = {
_pattern : /[a-zA-Z0-9_\-\+\.]/,
_getRandomByte : function()
{
// http://caniuse.com/#feat=getrandomvalues
if(window.crypto && window.crypto.getRandomValues)
{
var result = new Uint8Array(1);
window.crypto.getRandomValues(result);
return result[0];
}
else if(window.msCrypto && window.msCrypto.getRandomValues)
{
var result = new Uint8Array(1);
window.msCrypto.getRandomValues(result);
return result[0];
}
else
{
return Math.floor(Math.random() * 256);
}
},
generate : function(length)
{
return Array.apply(null, {'length': length})
.map(function()
{
var result;
while(true)
{
result = String.fromCharCode(this._getRandomByte());
if(this._pattern.test(result))
{
return result;
}
}
}, this)
.join('');
}
};