ffffff01 ffffff01 - 1 year ago 108
Javascript Question

Generate random password string with requirements in javascript

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 it doesn't meet my requirements.

var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
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);

Answer Source

Forcing a fixed number of characters is a bad idea. It doesn't improve the quality of the password. Worse, it reduces the number of possible passwords, so that hacking by bruteforcing becomes easier.

To generate a random word consisting of alphanumeric characters, use:

var randomstring = Math.random().toString(36).slice(-8);

How does it work?

Math.random()                        // Generate random number, eg: 0.123456
             .toString(36)           // Convert  to base-36 : "0.4fzyo82mvyr"
                          .slice(-8);// Cut off last 8 characters : "yo82mvyr"

Documentation for the Number.prototype.toString and string.prototype.slice methods.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download