create a password with a custom length and numbers in typescript

To create a password with a custom length and random numbers in Typescript, you can use the Math.random() method to generate a random number and convert that number to a character. Here's an example function that generates a password with a custom length and includes at least one number:

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

  // Ensure password includes at least one number
  if (!/\d/.test(password)) {
    const rnd = Math.floor(Math.random() * (length - 1));
    password = password.slice(0, rnd) + Math.floor(Math.random() * 10) + password.slice(rnd);
  }

  return password;
}
546 chars
17 lines

This function takes in a length parameter and uses it to generate a random password. It first creates a string of all possible characters that can be used to generate the password. Then, it iterates over the length parameter, generating a random index and appending the corresponding character to the password string.

After generating the initial password, it checks to ensure that there is at least one number included in the password. If not, it generates a random index and inserts a random number at that index.

You can call this function with a desired length parameter to generate a random password:

index.ts
const password = generatePassword(12); // Generates a password with length of 12
console.log(password); // Example output: "8JwZas6dhFq3"
138 chars
3 lines

gistlibby LogSnag