Generate random password string with requirements in javascript

前端 未结 20 1768
夕颜
夕颜 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

    For someone who is looking for a simplest script. No while (true), no if/else, no declaration.

    Base on mwag's answer, but this one uses crypto.getRandomValues, a stronger random than Math.random.

    Array(20)
      .fill('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$')
      .map(x => x[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)])
      .join('');
    

    See this for 0xffffffff.

    Alternative 1

    var generatePassword = (
      length = 20,
      wishlist = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$"
    ) => Array(length)
          .fill('')
          .map(() => wishlist[Math.floor(crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * wishlist.length)])
          .join('');
    
    console.log(generatePassword());
    

    Alternative 2

    var generatePassword = (
      length = 20,
      wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
    ) =>
      Array.from(crypto.getRandomValues(new Uint32Array(length)))
        .map((x) => wishlist[x % wishlist.length])
        .join('')
    
    console.log(generatePassword())
    

    Node.js

    const crypto = require('crypto')
    
    const generatePassword = (
      length = 20,
      wishlist = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@-#$'
    ) =>
      Array.from(crypto.randomFillSync(new Uint32Array(length)))
        .map((x) => wishlist[x % wishlist.length])
        .join('')
    
    console.log(generatePassword())
    

提交回复
热议问题