I am completing a telephone checker project and I am able to correctly identify the false results but the true ones are not returning true.
Here is my code so far. I have checked the individual functions and they all seem to work, although I have no knowledge of how to check for errors besides that. Any suggestions are greatly appreciated!
function telephoneCheck(str) {
let newStr = str;
let numberOfNumbers = 0;
if (newStr.match(/[!^A-Za-z!@#$%^&*_+=<>,.:]/gm) == []) {
for (let i = 0; i < newStr.length; i++) {
if (!isNaN(newStr[i])) {
numberOfNumbers += 1;
}
}
if (numberOfNumbers == 10) {
return true;
} else if (newStr[0] == 1) {
return true;
} else {
return false;
}
} else {
return false;
}
}
console.log(telephoneCheck("555-555-5555"));
Many issues. You cannot compare an array to an array, they are never the same
Here is what I think you wanted
const notNumDash= /[^\-0-9]/g; // something other than numbers and dashes
const telephoneCheck = str => {
if (notNumDash.test(str)) return false;
const numberOfNumbers = str.replace(/[^0-9]/g, ''); // remove all not numbers
return numberOfNumbers.length === 10 || numberOfNumbers[0] == 1; // either or returns true, all others false
}
console.log("555-555-5555",telephoneCheck("555-555-5555"));
console.log("5XXX55-555-5555",telephoneCheck("5XXX55-555-5555"));