Regex for Extracting Phone Numbers from Mixed Text in JavaScript - Handling Various Formats
This might be a silly question, but I'm trying to extract phone numbers from a block of mixed text using JavaScript and a regular expression, but I'm struggling to cover various formats. My input strings can contain phone numbers in several formats, such as `(123) 456-7890`, `123-456-7890`, `123.456.7890`, or even `+1 (123) 456 7890`. I've attempted the following regex pattern: ```javascript const text = "Call me at (123) 456-7890 or +1 (123) 456 7890 for more info."; const regex = /\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/g; const matches = text.match(regex); console.log(matches); ``` The `matches` array returns `['(123) 456-7890']`, but it fails to capture the `+1 (123) 456 7890` format. I'm also concerned about international numbers that might start with a `+` or have different spacing and separators. I've tried modifying the regex to include optional `+` and different separators, but it seems overly complicated and still doesn't work as expected. Here's a version that I thought might work: ```javascript const regex = /\+?\d*\s*\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}/g; ``` However, this still does not return the expected matches in some cases. If anyone has experience with regex for capturing phone numbers effectively in JavaScript, I would greatly appreciate your insights. Are there any best practices or commonly used patterns that could guide to refine my approach? Additionally, is there a way to ensure that my regex remains performant when processing large blocks of text? Thanks in advance for your help! How would you solve this? This is part of a larger application I'm building. Is there a better approach?