create a password with a custom length, uppercase letters and lowercase letters in typescript

index.ts
function generatePassword(length: number): string {
  const uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
  const allLetters = uppercaseLetters + lowercaseLetters;

  let password = "";
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * allLetters.length);
    password += allLetters[randomIndex];
  }

  return password;
}

console.log(generatePassword(10)); // Example output: "XgkRyjpfDu"
489 chars
16 lines

Here, we define a function generatePassword which takes in a length parameter specifying the desired length of our password. We define two constants uppercaseLetters and lowercaseLetters which contain all uppercase and lowercase letters respectively. We then concatenate these two strings into a single string allLetters.

We then use a for loop to iterate length number of times, each time generating a random index within the bounds of allLetters using Math.random() multiplied by the length of allLetters. We then concatenate the character at that random index to our password string.

Finally, we return the generated password. This function creates a strong password with the specified length and a mix of uppercase and lowercase letters.

gistlibby LogSnag