phone number rexexp in javascript

index.tsx
const phoneNumberRegex = /^\d{3}-\d{3}-\d{4}$/;

function validatePhoneNumber(inputPhoneNumber) {
  if (!phoneNumberRegex.test(inputPhoneNumber)) {
    return false;
  }
  return true;
}

console.log(validatePhoneNumber('123-123-1234')); // true
console.log(validatePhoneNumber('abc-def-ghij')); // false
305 chars
12 lines

In the above code block, we define a regular expression that matches the standard US phone number format, which is ###-###-####. We then define a function called validatePhoneNumber which takes an input phone number and returns true if it matches the expected format or false if it does not.

gistlibby LogSnag