JAVASCRIPT
Extracting Phone Numbers from Text
Learn to efficiently extract various common phone number formats (e.g., (123) 456-7890, 123-456-7890) from any text using a flexible regular expression pattern in JavaScript.
const text = "Contact us at (123) 456-7890 or call 987.654.3210. Our office number is 555-123-4567.";
const phoneNumberRegex = /\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g;
const phoneNumbers = text.match(phoneNumberRegex);
console.log(phoneNumbers);
// Expected output: ["(123) 456-7890", "987.654.3210", "555-123-4567"]
How it works: This snippet uses a regular expression to find common US-style phone number patterns within a string. It accounts for optional parentheses around the area code `\(?\d{3}\)?`, followed by optional separators like hyphens, periods, or spaces `[-.\s]?`, and then the last two sets of three and four digits `\d{3}[-.\s]?\d{4}`. The `g` flag ensures all matches are found.