Fastest method for testing a fixed phone number pattern

后端 未结 6 1876
孤街浪徒
孤街浪徒 2021-01-05 20:11

So, the challenge is that we are trying to detect if a string matches a fixed phone number pattern, this is a simple string pattern.

The pattern is:

         


        
6条回答
  •  一整个雨季
    2021-01-05 20:53

    very fast:

       function tecjam3(pattern) {
      if (pattern.length !== 12) {
        return false;
      }
    
      code = pattern.charCodeAt(0);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(1);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(2);
      if (code < 48 || code > 57) return false;
    
      code = pattern.charCodeAt(4);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(5);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(6);
      if (code < 48 || code > 57) return false;
    
      code = pattern.charCodeAt(8);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(9);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(10);
      if (code < 48 || code > 57) return false;
      code = pattern.charCodeAt(11);
      if (code < 48 || code > 57) return false;
    
      if (pattern.charAt(3) != '-' || pattern.charAt(7) != '-') return false;
    
      return true;
    }
    

提交回复
热议问题