create a password with a custom length and symbols in javascript

Here is a simple function that generates a random password with a length specified by the user, including symbols:

index.tsx
function generatePassword(length) {
  var charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+~`|}{[]\:;?><,./-=";
  var password = "";
  for (var i = 0; i < length; i++) {
    var randomNumber = Math.floor(Math.random() * charset.length);
    password += charset.substring(randomNumber,randomNumber+1);
  }
  return password;
}

console.log(generatePassword(10)); // Generates a random password with a length of 10
449 chars
12 lines

In this example, the generatePassword() function takes one argument length, which is the desired length of the password. The charset string includes all possible characters that can be used in the password, including letters (upper and lowercase), numbers, and symbols.

The function then iterates length number of times, generating a random number between 0 and the length of the charset string, and using that number to select a random character from the charset. The selected character is added to the password string.

Finally, the function returns the generated password. You can call the generatePassword() function and pass in any desired length argument to generate a custom password.

gistlibby LogSnag