create a password with at least one number in javascript

One way to create a password with at least one number is to use a regular expression to validate the input. Here is an example function that generates a random password with at least one number:

index.tsx
function generatePassword(length) {
  var password = "";
  var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  
  // Loop until we have at least one number in the password
  while (!/\d/.test(password)) {
    for (var i = 0; i < length; i++) {
      password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
  }
  
  return password;
}

console.log(generatePassword(8)); // e.g. "gH72aBz9"
434 chars
16 lines

The length parameter specifies the length of the password to generate. The chars string contains all possible characters that can be used in the password. The while loop keeps generating a new password until at least one digit is included in the password, by checking if the regular expression /d/ matches the password.

gistlibby LogSnag