My code is setup to check for special characters inside of a given password. The program is suppose to store true to a variable if a special character was found, and false if one was not found; Afterwards, it will print the result of the variable. The problem is the program keeps printing out false even when there's a special character inside of the password. I don't know what's wrong
const arrayOfSp = ["!", "@", "#", "$", "%", "&", "*", "_", "-", "?"];
const password = "Patrick_";
let specialCharacterCheck = false;
const special = (c) => {
for (i = 0; i < arrayOfSp.length; i++) {
if (c === arrayOfSp[i]) {
return true;
}
}
return false;
}
for (i = 0; i < password.length; i++) {
if (special(password[i])) {
specialCharacterCheck = true;
}
}
console.log(specialCharacterCheck);
You need to break from the loop as soon as it finds a special character. To find special character in the array you can use find which will return undefined is no matching character is found
const arrayOfSp = ["!", "@", "#", "$", "%", "&", "*", "_", "-", "?"];
const password = "Patr_ick";
let specialCharacterCheck = false;
const special = (c) => {
return arrayOfSp.find(item => item === c)
}
for (let i = 0; i < password.length; i++) {
const isPresent = special(password[i]);
if (isPresent) {
specialCharacterCheck = true;
break;
}
}
console.log(specialCharacterCheck);
You can simply use some and Set here
const arrayOfSp = ["!", "@", "#", "$", "%", "&", "*", "_", "-", "?"];
const password = "Patrick_";
const specialChars = new Set(arrayOfSp);
let specialCharacterCheck = [...password].some((c) => specialChars.has(c));
console.log(specialCharacterCheck);
I like using a regex approach here:
var arrayOfSp = ["!", "@", "#", "$", "%", "&", "*", "_", "?", "-"];
var password = "Patrick_";
var regex = "[" + arrayOfSp.join("") + "]";
if (new RegExp(regex).test(password)) {
console.log("Password is valid");
}
else {
console.log("Password is invalid");
}
Note that I have deliberately placed - at the end of your input array, to avoid including an unwanted range of characters in the character class.