CodexBloom - Programming Q&A Platform

Regex implementing International Phone Number Formatting in JavaScript - implementing Variants

πŸ‘€ Views: 68 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-08
regex javascript validation JavaScript

I've been working on this all day and I'm wondering if anyone has experience with I'm working on a personal project and I'm trying to create a regex pattern to validate international phone numbers in JavaScript, but I'm running into problems with different formats and lengths. The regex I initially wrote is supposed to match numbers in formats like +1234567890, (123) 456-7890, and 123-456-7890. However, it's not capturing numbers that start with a '+' sign correctly. Here's the regex I'm using: ```javascript const regex = /^(\+\d{1,3})?[-.\s]?\(?\d{1,4}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/; ``` I've tested it with a few cases, but it fails when I try inputs like '+44 20 7946 0958' or '0044 20 7946 0958'. Instead of matching, I get `null`. I've tried tweaking the pattern to accommodate optional spaces and parentheses, but it seems to complicate things further. Here’s a sample function for testing: ```javascript function validatePhoneNumber(number) { return regex.test(number); } console.log(validatePhoneNumber('+44 20 7946 0958')); // Should return true console.log(validatePhoneNumber('0044 20 7946 0958')); // Should return true console.log(validatePhoneNumber('123-456-7890')); // Should return true console.log(validatePhoneNumber('1234567890')); // Should return true console.log(validatePhoneNumber('abc-456-7890')); // Should return false ``` I'm using Node.js v14.17.0 and have tested it in various browsers too. Any suggestions on how to improve this regex to handle these cases properly? I also want to ensure it performs well as I'm validating phone numbers in a large dataset, so if there are any performance considerations, I'd love to hear about those too. Thanks! What am I doing wrong? For context: I'm using Javascript on macOS. Am I missing something obvious? I'm using Javascript latest in this project. Am I approaching this the right way?