I want to generate a random password of length of 16 characters containing numbers, alphabets and special characters, but no two special characters should be adjacent
the special characters i am using are ~!@#$%^&*()_+-={}[]:;\?,.|\\
generateRandomPasswordSelection = function (length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~!@#$%^&*()_+-={}[]:;\?,.|\\';
var result ='';
for(var i=1; i>=1;i++){
result = '';
for (var i = length; i > 0; --i) result += mask[Math.round(Math.random() * (mask.length - 1))];
if(result.match(new RegExp(/(?!.*[~!@#$%^&*()_+={}[\]:;\?,.|\\-]{2})[A-Za-z0-9]{1,16}$/))){
console.log(result,'---------------->', 'BREAk')
break;
}
}
}
generateRandomPasswordSelection(16,'aA#!');
Above one is the code i have tried, but didn't work.How to achieve this?
Uses ES6 syntax, hopefully more readable.
const getRandomElement = arr => {
const rand = Math.floor(Math.random() * arr.length);
return arr[rand];
}
const generateRandomPasswordSelection = (length) => {
const uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const special = ['~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '{', '}', '[', ']', ':', ';', '?', ', ', '.', '|', '\\'];
const numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const nonSpecial = [...uppercase, ...lowercase, ...numbers];
let password = '';
for (let i = 0; i < length; i++) {
// Previous character is a special character
if (i !== 0 && special.includes(password[i - 1])) {
password += getRandomElement(nonSpecial);
} else password += getRandomElement([...nonSpecial, ...special]);
}
return password;
}
const password = generateRandomPasswordSelection(16);
console.log(password);