I have two arrays:
enteredCommands = ["valid", "this", 1.1];
validParameters = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];
I want to loop through all of the enteredCommands, if it exists in validParameters remove it from validParameters, if it doesn't, break.
I don't know how to compare the regex in this way, if I change validParameters to:
validParameters = ["valid", "alsoValid", /this|that/, /\d+(\.)?\d*/];
and use:
var ok2go = true;
// For each entered command...
for (var i = 0; i < commands.length; i++) {
// Check to see that it is a valid parameter
if (validParameters.indexOf(commands[i]) === -1) {
// If not, an invalid command was entered.
ok2go = false;
break;
// If valid, remove from list of valid parameters so as to prevent duplicates.
} else {
validParameters.splice(validParameters.indexOf(commands[i]), 1);
}
return ok2go;
}
if (ok2go) {
// do stuff if all the commands are valid
} else {
alert("Invalid command");
}
It works the way I want it to for the strings, but obviously not for those values that need to be regex. Is there any way to solve this?
Test cases:
enteredCommands = ["valid", "this", 1.1, 3];
// Expected Result: ok2go = false because 2 digits were entered
enteredCommands = ["valid", "alsoValid", "x"];
// Expected Result: ok2go = false because x was entered
enteredCommands = ["valid", "alsoValid", 1];
// Expected Result: ok2go = true because no invalid commands were found so we can continue on with the rest of the code
enteredCommandsexist invalidParametersonly once. Hence: "I want to loop through all of theenteredCommands, if it exists invalidParametersremove it fromvalidParameters, if it doesn't, break."