I’m trying to avoid using Regex as much as I can because I hate it. So my plan is to remove all characters except numbers from the string.This way will be easier to check if the number provided has 11 characters and the first one is different than 1. If this condition is true, return false. My code is working with most numbers except for (“1 555-555-5555”) , (“1 (555) 555-5555”), (“1(555)555-5555”) , (“1 555 555 5555”), (“1 456 789 4444”) .
function telephoneCheck(str) {
var replace = str.replace(/[\D]/g, '').replace(/["'()]/g, "").replace(/["'()]/g, "").replace(/ /g, "").replace(/-/g, "");
if (replace.length === 11 && replace.charCodeAt(0) !== 1) {
return false;
}
var pattern = '';
for (var i = 0; i < str.length; i++) {
pattern += str[i] >= '0' && str[i] <= '9' ? 'x' : str[i];
}
return ['xxx-xxx-xxxx', 'xxxxxxxxxx', '(xxx)xxxxxxx', '(xxx)xxx-xxxx', 'xxx xxx xxxx', 'x xxx xxx xxxx', 'x-xxx-xxx-xxxx', 'xxxxxxxxxxx', 'x(xxx)xxxxxxx', 'x(xxx)xxx-xxxx', 'x xxx xxx xxxx', 'x xxx-xxx-xxxx', 'x (xxx) xxx-xxxx']
.indexOf(pattern) >= 0;
}
telephoneCheck("1 555-555-5555");
https://www.freecodecamp.org/challenges/validate-us-telephone-numbers