function randomPassword() {
let length = 15,
password = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",
space = "";
for (let i = 0, mu = password.length; i < length; i) {
space = password.charAt(Math.random() * mu)
}
return space;
}
console.log(randomPassword());
I'm new at javascript. I finally made this code but i don't want it to create a password that starts with "-", "_", "0". How can i do that?
CodePudding user response:
We keep the _
, -
and 0
away from the character string while we generate the first character for the password. After generating the first character, we add the _
, -
and 0
back to the character string and generate the rest of the characters for the password.
function randomPassword() {
let length = 15;
// Initial characters without -, _ or 0
let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
// Generate first character
let password = characters.charAt(Math.floor(Math.random() * characters.length 1));
// Add the symbols now
characters = "-_0";
// Generate rest
for (let i = 0; i < length; i ) {
password = characters.charAt(Math.floor(Math.random() * characters.length 1));
}
// Return
return password;
}
console.log(randomPassword());
CodePudding user response:
Another approach can be something like this :
function generatePassword() {
var length = 15,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",
retVal = "";
for (var i = 0, n = charset.length; i < length; i) {
let charOne = charset.charAt(Math.floor(Math.random() * n));
if (i == 0) {
while (charOne == "-" || charOne == "_" || charOne == "0")
charOne = charset.charAt(Math.floor(Math.random() * n));
}
retVal = charOne
}
return retVal;
}
console.log(generatePassword())