Recipe 34 | Using Special Replacement Patterns |
Task
Imagine you have a private group web page where members agreed to share their contact information with other members. You don’t want to impose any restrictions on the phone number format the website accepts other than it should consist of ten digits. So, a user might enter 123-456-7890, 123 456 7890, or (123)4567890.
But you want to transform the digits into a formatted phone number so they will display consistently, like (123) 456-7890, throughout the website. To achieve this, you first need to remove any existing formatting from the number and then format it the way you want.
Solution
Remove all formatting by replacing non-digit characters with an empty string:
Get Text Processing with JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.