random string

213 阅读1分钟
// 字符集包括数字大小写字母
// repeat 为 true , ignoreCase 无效
// repeat 为 false , ignoreCase 为 true , 字符集为 36 : 0-9a-z
// repeat 为 false , ignoreCase 为 false , 字符集为 62 : 0-9a-zA-Z
function randomStr(strLength = 6, repeat = false, ignoreCase = false) {
    let validCharacter = "0123456789";
    const aIndex = "a".charCodeAt();
    const AIndex = "A".charCodeAt();
    for (let i = aIndex; i < aIndex + 26; i++) {
        validCharacter += String.fromCharCode(i);
    }
    for (let i = AIndex; i < AIndex + 26; i++) {
        validCharacter += String.fromCharCode(i);
    }
    validCharacter = validCharacter.split("");
    let result = '';
    if (repeat) {
        for (let i = 0; i < strLength; i++) {
            result += validCharacter[Math.floor(Math.random() * validCharacter.length)];
        }
    } else {
        ignoreCase && strLength > 36 ? strLength = 36 : void 0;
        ignoreCase && validCharacter.splice(36, 26);
        //console.log("current characters : ", validCharacter.join(","));
        !ignoreCase && strLength > 62 ? strLength = 62 : void 0;
        while (result.length < strLength) {
            const newCharacterIdx = Math.floor(Math.random() * validCharacter.length);
            const newCharacter = validCharacter.splice(newCharacterIdx, 1)[0];
            result += newCharacter;
        }
    }
    return result;
}
console.log(randomStr(64, false, false));