Fastest method for testing a fixed phone number pattern

后端 未结 6 2005
孤街浪徒
孤街浪徒 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:41

    Declaring a regex object pre-compiles it for any future use. Since you are looping through several test strings, it should perform better to instantiate the object outside the function first:

    var rex = /^\d{3}-\d{3}-\d{4}$/;
    

    Then the function would be:

    function matchesPattern(pattern) {
        return rex.test(pattern);
    }
    

提交回复
热议问题