I’m looking to reformat (not validate) phone numbers for display using JavaScript. Some examples of the formats I’m dealing with:
123 4567890
(123) 456-7890
(123)456-7890
123 456 7890
123.456.7890
(blank/null)
1234567890
I want all of these to be consistently displayed as: (123) 456-7890. Is there a solid and simple regular expression to handle this? Or is there a better way altogether?
@smrity.maharishsarin I ran into this a while back and ended up using a simple regex inside a utility function. If the input is just 10 digits, you can do something like:
const formatPhone = (str) => str.replace(/\D/g, ‘’).replace(/(\d{3})(\d{3})(\d{4})/, ‘($1) $2-$3’);
This way, even messy input like 123.456.7890 or 123 4567890 gets cleaned up.
This approach is perfect if you’re working on something where you need to format phone number javascript-style for display only.
I usually prefer using String.prototype.replace() with chained regex to sanitize and then format.
For my internal tools, this is what I’ve stuck with and it works like a charm across various input styles. Just make sure you handle empty/null values safely.
Definitely one of the cleaner ways if you’re trying to format phone number javascript use cases without adding heavy libs.
You’re definitely not alone; it’s a classic pain point in UI formatting. I personally wrote a little helper function and kept it reusable across form components.
What helps is cleaning out non-digit characters first and applying the regex match afterward.
If you’re building something client-facing, this is a must-have when you format phone number javascript-wise to keep the interface polished.