create a password with a custom length and numbers in javascript

You can use the following code to generate a random password with a custom length that includes numbers:

index.tsx
function generatePassword(length) {
  // define all possible characters
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
  
  let password = '';
  
  // loop through desired password length
  for(let i = 0; i < length; i++) {
    // get random character from chars string
    const randomChar = chars.charAt(Math.floor(Math.random() * chars.length));
    
    // add character to password string
    password += randomChar;
  }
  
  return password;
}

// calling the function with length argument of 8
console.log(generatePassword(8)); // output example: 'A6cF23gT'
600 chars
21 lines

Explanation:

  • The chars variable defines all the possible characters that can be used in the password. It includes alphabets (both uppercase and lowercase) and numbers.
  • The generatePassword function accepts a length argument that specifies the desired length of the password.
  • We initialize an empty string called password
  • We loop through the desired length and concatenate a random character (using the charAt() method and Math.random() function) to the password string on each iteration.
  • Finally, we return the completed password string.

gistlibby LogSnag