I am making a random password-generation app using JS.
Following is an array of special characters which I am using to generate random special characters:
const specialChars = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~', '\'];
In the app, I get two backslashes when I try to add a backslash to the password during generation using the above array:
specialChars[genRandNum(0, specialChars.length-1)];
genRandNum() function generates a random number b/w given range.
In this case, it generates a random number b/w 0 and last index of specialChars i.e. specialChars.length-1
So whenever a backslash \ is chosen randomly from specialChars array it should have printed only 1 backslash but it is printing the backslash twice.
Following is the code for the genRandChar() function for generating a random character:
const genRandChar = (choice) => {
switch(choice) {
case 1:
return genRandAscii(65, 90); //For generating Capital letters
case 2:
return genRandAscii(97, 122); //For generating Small letters
case 3:
return genRandNum(0, 9); //For generating random number b/w 0 to 9
case 4:
return specialChars[genRandNum(0, specialChars.length-1)]; // for special chars
}
}
genRandAscii() generates a random character bw given Ascii values
Following is the code for generating random password using capital letters, small letters, numbers(0 to 9) and special characters using genRandChar() function:
const genPassword = (filter) => {
let password = "";
const length = genRandNum(filter.min, filter.max);
for(let i=1; i<=length; i++) {
password += genRandChar(genRandNum(1, 4));
}
return {password: password, length: length, actualLength: password.length};
}
Sample Output of genPassword() function:
{ password: "OZ'Wl\p6", length: 8, actualLength: 8 }
In the above sample output as you can see that it was supposed to print only one backslash but it is printing twice due to which the actual length became 9 (count it) which should be 8 if only one backslash was printed.
The length which was chosen randomly i.e. length and actualLength i.e. equal to password.length is 8 only. So on counting also it should be 8 but it is 9.
Please tell me how to solve the problem.