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
This isn't exactly optimized, but it should work.
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
var charCount = 0;
var numCount = 0;
for (var i=0; i= 5) {
var rnum = Math.floor(Math.random() * 10);
randomstring += rnum;
numCount += 1;
} else {
// If any of the above criteria fail, go ahead and generate an alpha character from the chars string
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
charCount += 1;
}
}
alert(randomstring);
Here's a jsfiddle for you to test on: http://jsfiddle.net/sJGW4/3/