DEV Community

Chandra Prakash Pal
Chandra Prakash Pal

Posted on

Generate minimum 8 character password with at least one lowercase,one uppercase,one number and one special character.

function generatePassword() {
  let pass = ''
  const charArr = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '0123456789', '@#$'];
  const str = charArr.join('');
  for (let i = 0; i <= 8; i++) {
    const index = Math.floor(Math.random() * str.length + 1);
    pass += str.charAt(index)
  }
  if (!pass.checkExist(charArr[0])) {
    const x = Math.floor((Math.random() * 25) + 1);
        const upcChar=charArr[0].split('')
        console.log('upc',x,upcChar)
    pass+=upcChar[x]
  }
  if (!pass.checkExist(charArr[1])) {
    const x = Math.floor((Math.random() * 25) + 1);
        const lwcChar=charArr[1].split('')
        console.log('lwc',x,lwcChar)
    pass+=lwcChar[x]
  }
  if (!pass.checkExist(charArr[2])) {
    const x = Math.floor((Math.random() * 9) + 1);
        const numChar=charArr[2].split('')
        console.log('num',x,numChar)
    pass+=numChar[x]
  }
  if (!pass.checkExist(charArr[3])) {
    const x = Math.floor((Math.random() * 2) + 1);
        const splChar=charArr[3].split('')
        console.log('spl',x,splChar)
    pass+=splChar[x]
  }
  return pass;
}
console.log(generatePassword())
Output:-
eYc$8O9Xf
Enter fullscreen mode Exit fullscreen mode

Top comments (0)