Validate US Telephone Numbers - Help with my code

Validate US Telephone Numbers - Help with my code
0

#1

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");

#2

Maybe you meant any of the following?

replace[0] !== '1'
replace[0] != 1
replace.charCodeAt(0) != 49

#3

Could you please explain me why did the above one work I have no idea.


#4

.charCodeAt() gets the ASCII code (Unicode actually, but for common strings, you can think of ASCII) of the char at the specified position. The ASCII code for the character 1 is 49.