A tip for "Validate US Telephone Numbers"

A tip for "Validate US Telephone Numbers"
0

#1

I think a lot of people (me included) find regexes tricky and developing a single regex that covers all the test cases frustrating. I couidn’t understand the long regexes in the hint, and would have gained nothing by copying them.

Here is a gentler approach other people may also find it useful: build an array of regexes*, then use Array.some to return true for any phone number that matches one of these.

Finding a set of regexes satisfying the test cases one by one is easier than finding a single all-encompassing solution, and they can be generalised and whittled down. (Perhaps to one, perhaps several - in particular I don’t know how to check for unmatched parentheses with regex - but anyway this is a low-stress opportunity to get to know regexes better.)

function telephoneCheck(str) {
  var reArr = [/^\d{3}-\d{3}-\d{4}/,
              ...more regexes...
              ];
  res = reArr.some(
    function (re) {
      console.log(str, re, re.test(str)); // see which regex is passing each test case
      return re.test(str);
  });
  console.log("========================="); // visually separate test cases
  return res;  
}

*it’s also possible to fill the array with string representations of regexes, rather than literal regex objects, and compile them to regexes with something like:

var myRe = new RegExp(regexSstring, regexFlags)

but this involves a lot of escaping with backslashes…

Link to the challenge:


#2

I learned the HTML input pattern attribute today, and was blown away by the inclusion of some form of regular expressions in a markup language.

RegExr.com is great for building a pattern for a specific body of text (or source code). Probably the best simple expression tool I’ve used, and gives you a chance to play around with patterns.