create a password with uppercase, lowercase letters and numbers in typescript

To create a random password in TypeScript that contains uppercase, lowercase letters, and numbers, you can use the following code:

index.ts
function generatePassword(length: number): string {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let password = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    password += chars.charAt(randomIndex);
  }
  return password;
}

const password = generatePassword(8); // generates a password with length of 8
console.log(password); // output: Zm92k7pL
449 chars
13 lines

This code defines a generatePassword function that takes a length parameter and returns a randomly generated password string of that length. The chars constant contains all the possible characters that the password can contain, and the function uses a loop to pick random characters from chars until the desired length is reached. Finally, the function returns the password string.

You can adjust the length of the password by passing a different number to generatePassword. This code should generate a strong password with a good mix of uppercase, lowercase letters, and numbers, but keep in mind that the randomness of this algorithm may not be sufficient for extremely secure applications.

gistlibby LogSnag