randomPassword()
💾 replit
// ⭐️ 預設密碼長度:32
function randomPassword(length = 32, {
digit = true, // 要有數字
lowercase = true, // 要有小寫
uppercase = true, // 要有大寫
underscore = true, // 可以有 "_"
symbol = true, // 特殊符號
}={}){
// 1. 字集
let digits = String.fromCharCodesBetween(48, 57); // '0...9'
let letters = String.fromCharCodesBetween(97, 122); // 'a...z'
let capitals = String.fromCharCodesBetween(65, 90); // 'A...Z'
let symbols = "!@#$%^&*";
let underscores = "_";
// 2. 準備組合密碼
let pwd = ''; // 密碼
let candidates = ''; // 密碼候選字
// 3. 從必用的字集中選字
[
[digit, digits], // 數字
[lowercase, letters], // 小寫
[uppercase, capitals], // 大寫
[underscore, underscores], // 底線 "_"
[symbol, symbols], // 特殊符號
].forEach(([include, chars]) => {
if(include){ // 如果要加入
pwd += chars.random(); // 先加入一個字元
candidates += chars; // 整組字集加入候選字
}
});
// 4. 如果密碼長度不足,就繼續選字
let k = pwd.length; // 目前密碼長度
let n = candidates.length; // 選用字總長度
while(k < length){
pwd += candidates.random();
k += 1;
}
return pwd.shuffle();
}
Last updated
Was this helpful?