I want to generate a random string that has to have 5 letters from a to z and 3 numbers.
How can I do this with JavaScript?
I've got the following script, but it doesn't meet my requirements.
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
Update 2025:
It's been 13 years since I first asked this question as a complete beginner—both in tech and in the working world. I'm amazed at how many discussions and different answers it has sparked over the years.
I’d like to clarify now that the code in the original post was simply meant to generate a one-time password (OTP) for a single-use scenario. It was sent via email and only needed to live for about 2–3 minutes, so strong randomness or cryptographic methods weren’t really a concern.
Still, it's been fun to stop by now and then to see all the creative suggestions. Thanks to everyone who contributed—it's been a great ride!
new Array(12).fill().map(() => String.fromCharCode(Math.random()*86+40)).join("")Nifty one liner to produce a 12 char password with special chars upper lower numbers in a very lightweight approach