create a password with a custom length and symbols in typescript

Here's an example function that generates a random password with any symbols and custom-length in TypeScript:

index.ts
function generatePassword(length: number): string {
  const symbols = '!@#$%^&*()_-+={}[];:,.<>?/|~';
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' + symbols;
  let password = '';

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

  return password;
}

// Example usage to generate a password with 12 characters including symbols:
const password = generatePassword(12);
console.log(password); // outputs something like: "Gm{2r]&u%7q0"
558 chars
17 lines

In the function, we first define the custom set of symbols that we want to use in the password. Then, we combine these symbols with a set of alphanumeric characters to create a charset variable.

We then loop over the length parameter and randomly select a character from the charset string for each iteration. Finally, we return the generated password string.

You can adjust the length parameter to generate a password of any desired length.

gistlibby LogSnag