简体   繁体   English

一种检查字符串是否包含来自特定 substring 的字符的方法

[英]A way to check if a string contains a character from a specific substring

I'm doing a coding boot camp and our objective is to set up a password generator that a user selects which type of characters (lowercase, uppercase, number, and special) and a length and it provides them with a random secure password.我正在做一个编码训练营,我们的目标是设置一个密码生成器,用户可以选择哪种类型的字符(小写、大写、数字和特殊字符)和长度,并为他们提供一个随机的安全密码。

I am able to get all aspects of this to work, aside from an important part of the assignment which is that the generated password must include each character the user selected.除了作业的一个重要部分,即生成的密码必须包含用户选择的每个字符外,我能够使它的所有方面都起作用。 It's currently grabbing at random, so it's not always guaranteed if you choose all 4 criteria that they will all appear.它目前是随机抓取的,因此如果您选择所有 4 个条件,它们将全部出现并不总是保证。 How can I validate this?我如何验证这一点?

const lowCaseArr = "abcdefghijklmnopqrstuvwxyz";
const upCaseArr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numeralArr = "1234567890";
const specialArr = "!@#$%^&*";

function getLength() {
    while (true) {
        var userLength = parseInt(prompt("How many numbers, between 8 and 128, would you like to use? (Enter 0 to cancel)"));
        if (userLength == 0) {
            return 0;
        } else if (userLength > 128 || userLength < 8) {
            alert("You must enter a number between 8-128.");
        } else if (userLength <= 128 && userLength >= 8) {
            alert("Great! Your have selected a password with " + userLength + " characters.");
            return userLength;
        }
    } 
}

function randChar(passwordCharacters) {
    return passwordCharacters.charAt(Math.floor(Math.random() * passwordCharacters.length));
}

function makePassword(userLength, passwordCharacters) { 
    var securePassword = "";
    for (i = 0; i < userLength; i++) {    
        securePassword += randChar(passwordCharacters);
    }
    return securePassword;
}

function generatePassword() {
    var userLength = getLength();
    if (userLength == 0) {
        return "User Cancelled Request";
    }


    var passwordCharacters = "";
    var askLowerCase = confirm("Would you like to include lower case characters? (a, b, c)");
    if (askLowerCase !== true) {
        alert("Got it. No lower case characters will be included.");
    } else {
        alert("Great! Your password will include lower case characters!");
        passwordCharacters += lowCaseArr;
    }

    var askUpperCase = confirm("Would you like to include upper case characters? (A, B, C)");
    if (askUpperCase !== true) {
        alert("Got it. No upper case characters will be included.");
    } else {
        alert("Great! Your password will include upper case characters!");
        passwordCharacters += upCaseArr;
    }

    var askNumerals = confirm("Would you like to include numeral characters? (1, 2, 3)");
    if (askNumerals !== true) {
        alert("Got it. No numeral characters will be included.");
    } else {
        alert("Great! Your password will include numeral characters!");
        passwordCharacters += numeralArr;
    }

    var askSpecial = confirm("Would you like to include special characters? (~, !, @)");
    if (askSpecial !== true) {
        alert("Got it. No special characters will be included.");
    } else {
        alert("Great! Your password will include special characters!");
        passwordCharacters += specialArr;
    }    

    var basePassword = makePassword(userLength, passwordCharacters);

    var securePassword = validateOptions(basePassword, askLowerCase, askUpperCase, askNumerals, askSpecial);
    return securePassword;

}

var generateBtn = document.querySelector("#generate");

function writePassword() {
    var password = generatePassword();
    var passwordText = document.querySelector("#password");

    passwordText.value = password;
}

generateBtn.addEventListener("click", writePassword);

My thought is to create a function that validates password, I'm just not sure what the best logic is here.我的想法是创建一个 function 来验证密码,我只是不确定这里最好的逻辑是什么。

function validateOptions(basePassword, askLowerCase, askUpperCase, askNumerals, askSpecial) {

    var securePassword = basePassword;

    // while (missing requirements) {
    // Validate that all selected characters have been included

    //  if securePassword does not contain lowercase, 
    //      then replace a random char in string with lowercase character
    //  if securePassword does not contain uppercase,
    //      then replace a random char in string with uppercase character
    //  if securePassword does not contain numbers,
    //      then replace a random char in string with numeral character
    //  if securePassword does not contain special characters,
    //      then replace a random char in string with a special character
    //  }
    
    return securePassword;
}

Rather than alter the password after the fact, you can generate it properly from the beginning by ensuring it meets all the constraints.与其在事后更改密码,不如通过确保密码满足所有约束从一开始就正确生成密码。

I've taken pieces of your code to produce a standalone function makeSecurePassword() which accepts several arguments: userLength , askLowerCase , askUpperCase , askNumerals , askSpecial .我已经使用了您的代码片段来生成一个独立的 function makeSecurePassword() ,它接受多个 arguments: userLengthaskLowerCaseaskUpperCaseaskNumeralsaskSpecial It returns a password of the requested userLength , containing only the types of characters requested.它返回请求的userLength的密码,仅包含请求的字符类型。 It uses your randChar() helper function.它使用您的randChar()助手 function。

var securePassword = makeSecurePassword( 10, true, true, true, true );

console.log(securePassword);

// Return a random character from passwordCharacters:
function randChar(passwordCharacters) {
    return passwordCharacters.charAt(Math.floor(Math.random() * passwordCharacters.length));
}

function makeSecurePassword( userLength, askLowerCase, askUpperCase, askNumerals, askSpecial ) {
    const lowCaseArr = "abcdefghijklmnopqrstuvwxyz";
    const upCaseArr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const numeralArr = "1234567890";
    const specialArr = "!@#$%^&*";

    var password = [];

    // Decide which chars to consider:
    charArray = [];
    if ( askLowerCase ) {
        charArray.push( lowCaseArr );
    }
    if ( askUpperCase ) {
        charArray.push( upCaseArr );
    }
    if ( askNumerals ) {
        charArray.push( numeralArr );
    }
    if ( askSpecial ) {
        charArray.push( specialArr );
    }
    
    let x = 0; // index into charArray
    for ( var i=0; i < userLength; i++ ) {
        var a = charArray[x]; // Which array of chars to look at

        // Insert at random spot:       
        password.splice( password.length, 1, randChar( a ) );

        // Pick next set of chars:
        if ( ++x >= charArray.length ) {
            x = 0; // Start with the first set of chars if we went past the end
        }
    }

    return password.join(''); // Create a string from the array of random chars
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM