Generate random password string with requirements in javascript

前端 未结 20 1703
夕颜
夕颜 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:09

    I have written a small one inspired from your answer:

    (function(){g=function(){c='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';p='';for(i=0;i<8;i++){p+=c.charAt(Math.floor(Math.random()*62));}return p;};p=g();while(!/[A-Z]/.test(p)||!/[0-9]/.test(p)||!/[a-z]/.test(p)){p=g();}return p;})()
    

    This function returns the password and can be used in bookmarklet like:

    javascript:alert(TheCodeOfTheFunction);
    

提交回复
热议问题