Common Patterns: URL & Phone — Regex

A "long digits" pattern eats the bank account too; a UK mobile pattern locks the prefix (?:\+44 ?|0)7, and (?<!\d) with (?!\d) refuses a digit run that is too…

In the PO chat, three people write a phone number in three styles: Dina 07700-900-123, Bayu +44 7700-900-456, Sari 07700900461. Same kind of data, different spelling. Like the street names "Jasmine St.", "Jasmine Street" and "Jasmine Str": people know it's the same street, but the courier's system keeps one form only. In this lesson regex is used twice: to find the phone numbers (without taking the bank account along) and then to tidy them into one form, +44.... Last, web addresses: regex to find them, new URL() to read them.

Three styles of phone number in the chat

Writer In the chat Style
Dina 07700-900-123 starts with 0, split by dashes
Bayu +44 7700-900-456 country code +44, a space, dashes
Sari 07700900461 starts with 0, no separator

A long-digits pattern eats the bank account too

console.log(chat.match(/\+?\d[\d -]{8,}\d/g));
// ['07700-900-123', '+44 7700-900-456', '1234567890', '07700900461']

A UK mobile number pattern

A UK mobile number starts with 07, or with +44 then 7. Use that to tell them apart.

const phonePattern = /(?<!\d)(?:\+44 ?|0)7\d{3}[- ]?\d{3}[- ]?\d{3}(?!\d)/g;
console.log(chat.match(phonePattern)); // ['07700-900-123', '+44 7700-900-456', '07700900461']

To check one form input, there's also the short pattern /^(\+44|0)\d{10}$/: it starts with +44 or 0, then 10 digits, and nothing else. 07700900461 passes, 1234567890 is turned down. But 07700-900-123 is turned down too because of its dashes, so tidy it before you check.

Tidy it into +44

function tidy(number) {
  return number.replace(/[^\d+]/g, "").replace(/^0/, "+44");
}

const phoneNumbers = chat.match(phonePattern).map(tidy);
console.log(phoneNumbers); // ['+447700900123', '+447700900456', '+447700900461']
console.log(phoneNumbers.every((n) => /^\+[1-9]\d{1,14}$/.test(n))); // true

URLs: regex to find them, new URL() to read them

The chat has no link yet. Say Mrs. Ratna sends one more message:

const message = "The full catalog is at https://example.com/catalog?cookie=tart. Order in the chat please";

console.log(/^https?:\/\/[\w.-]+/.test("https://example.com"));   // true
console.log(message.match(/https?:\/\/\S+/g));                     // ['https://example.com/catalog?cookie=tart.']
console.log(message.match(/https?:\/\/\S+?(?=[.,!?]?(?:\s|$))/g)); // ['https://example.com/catalog?cookie=tart']

Once it's found, don't take a URL apart with a regex. new URL() reads it with the same rules the browser uses:

const url = new URL("https://example.com/catalog?cookie=tart");
console.log(url.hostname);                   // 'example.com'
console.log(url.pathname);                   // '/catalog'
console.log(url.searchParams.get("cookie")); // 'tart'
new URL("example.com/catalog");              // TypeError: Invalid URL
console.log(URL.canParse("example.com"));    // false

⚠️ Bank accounts that get picked up, and links that run too far

TL;DR: A "long digits" pattern eats the bank account too; a UK mobile pattern locks the prefix (?:\+44 ?|0)7, and (?<!\d) with (?!\d) refuses a digit run that is too long. /^(\+44|0)\d{10}$/ checks a tidy UK mobile number: it starts with +44 or 0, then 10 digits. Tidy with .replace(/[^\d+]/g, "").replace(/^0/, "+44") into the E.164 format like +447700900123: a +, the country code, at most 15 digits, no separators. For URLs, /^https?:\/\/[\w.-]+/ recognises the start, a regex helps find links in a text (watch the punctuation at the end), and new URL() reads them: hostname, pathname, searchParams. A text that isn't a URL makes it throw a TypeError. In a real app, phone numbers are checked with libphonenumber-js.

⚡ Lock the prefix of a phone number

Write:

const phonePattern = /(?<!\d)(?:\+44 ?|0)7\d{3}[- ]?\d{3}[- ]?\d{3}(?!\d)/g;
console.log(chat.match(phonePattern));
Guess first: does the bank account 1234567890 get taken too?

No. The result is ['07700-900-123', '+44 7700-900-456', '07700900461']. The pattern locks the prefix, +44 or 0, then 7, and the account starts with 1. A pattern that only counts digits, like /\+?\d[\d -]{8,}\d/g, takes the account too.

Meaning: Same kind of data, three spellings. Lock what every phone number shares, not just its length.

⚡ Tidy it into +44

Write:

function tidy(number) {
  return number.replace(/[^\d+]/g, "").replace(/^0/, "+44");
}

Meaning: [^\d+] with the g flag throws away everything that isn't a digit or a +. Only a 0 at the start is replaced with +44. The result is the E.164 format, such as +447700900123.

⚡ URLs: regex to find, new URL() to read

Write:

console.log(/^https?:\/\/[\w.-]+/.test("https://example.com")); // true

Meaning: https?:\/\/ matches http:// and https://, then [\w.-]+ is the host name: letters, digits, dots, dashes. Once a URL is found, read it with new URL(), not with a regex.

What you will learn