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

Here is an example function that generates a password with a custom length and includes uppercase and lowercase letters:

index.tsx
function generatePassword(length) {
  var result           = '';
  var characters       = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  var charactersLength = characters.length;
  for ( var i = 0; i < length; i++ ) {
     result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

// Example usage: 
console.log(generatePassword(10)); // Output: "sJrBKDqtvX"
411 chars
13 lines

Explanation:

  • The function generatePassword takes a length parameter that specifies the desired length of the password.
  • By default, it uses only uppercase and lowercase letters in the characters string.
  • It then loops through the string length number of times and randomly selects a character to add to the result string using the Math.random() and charAt() methods.
  • Finally, it returns the generated password result.

gistlibby LogSnag