Generate random password string with requirements in javascript

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

    My Crypto based take on the problem. Using ES6 and omitting any browser feature checks. Any comments on security or performance?

    const generatePassword = (
      passwordLength = 12,
      passwordChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
    ) =>
      [...window.crypto.getRandomValues(new Uint32Array(passwordLength))]
        .map(x => passwordChars[x % passwordChars.length])
        .join('');
    

提交回复
热议问题