Generate random password string with requirements in javascript

前端 未结 20 1702
夕颜
夕颜 2020-12-07 07:56

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

20条回答
  •  攒了一身酷
    2020-12-07 08:07

    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/

提交回复
热议问题