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 plus sign may be there,\done digit,[\d -]{8,}at least 8 digits, spaces or dashes, then\dat the end.- The bank account
1234567890is also a "long run of digits", so it gets taken. The pattern only counts digits; it can't tell a phone number from a bank account.
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']
(?:\+44 ?|0): the prefix is+44(a space may follow) or0. Alternation inside a non-capturing group.7\d{3}: a UK mobile number goes on with7and three more digits, like7700.[- ]?: the separator is a dash, a space, or nothing.\d{3}then\d{3}: the rest of the number. In total that is 10 digits after the0, the length of a UK mobile number.(?<!\d)and(?!\d): no other digit may come right before or after the number. Without them,07700-900-1234is cut to07700-900-123, a wrong number with no error.- The account
1234567890starts with1, so it doesn't match.
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
[^\d+]with thegflag throws away everything that isn't a digit or a+: dashes and spaces.^0is replaced with+44: only a zero at the start. Bayu's number already starts with+44, so it stays as it is.- The result is the E.164 format, the international standard for phone numbers: a
+, the country code (its first digit isn't 0), at most 15 digits in all, no separators. Its pattern is/^\+[1-9]\d{1,14}$/.+447700900123is valid;07700900123(no+),+0770090(a country code starting with 0) and44-7700-900-123(separators) are not. - In a real app, use the
libphonenumber-jslibrary. It knows the length and prefixes of every country's numbers, which keep changing.
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']
https?:\/\/matcheshttp://andhttps://.[\w.-]+after it matches the host name: letters, digits, dots, dashes.\S+(everything that isn't whitespace) swallows the sentence's full stop too. The lazy\S+?with a lookahead "one punctuation mark may come, then a space or the end of the text" stops before that full stop.
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
- A text that isn't a full URL (here, no
https://) makesnew URL()throw a TypeError. The message can differ between browsers; the one above is Node's. URL.canParse()answerstrueorfalsewithout throwing.
⚠️ Bank accounts that get picked up, and links that run too far
- A pattern that only counts digits. Bank accounts, ID numbers and tracking numbers get taken. Lock the prefix:
0or+44, then7. - Forgetting the
gflag when tidying."07700-900-123".replace(/-/, "")only removes the first dash:'07700900-123'. - A
447...number without the plus.^0doesn't catch it. Add.replace(/^44/, "+44"). - A URL swallowing punctuation.
\S+carries along the dot or comma at the end of a sentence. Stop it with a lookahead, or tidy the end. new URL()acceptsjavascript:alert(1). Before you use one as a link, check thaturl.protocolishttps:orhttp:.
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.