Generate random password string with requirements in javascript

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

    I wouldn't recommend using a forced password as it restricts the User's Security but any way, there are a few ways of doing it -

    Traditional JavaScript Method -

    Math.random().toString(36).slice(-8);
    

    Using Random String

    Install random string:

    npm install randomstring
    

    Using it in App.js -

    var randStr = require('randomstring');
    
    var yourString = randStr.generate(8);
    

    The Value of your password is being hold in the variable yourString.

    Don't Use A Forced Password!

    Forced Password can harm your security as all the passwords would be under the same character set, which might easily be breached!

    0 讨论(0)
  • 2020-12-07 08:31
    var letters = ['a','b','c','d','e','f','g','h','i','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
        var numbers = [0,1,2,3,4,5,6,7,8,9];
        var randomstring = '';
    
            for(var i=0;i<5;i++){
                var rlet = Math.floor(Math.random()*letters.length);
                randomstring += letters[rlet];
            }
            for(var i=0;i<3;i++){
                var rnum = Math.floor(Math.random()*numbers.length);
                randomstring += numbers[rnum];
            }
         alert(randomstring);
    
    0 讨论(0)
提交回复
热议问题