Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse area code out of phone number

I have a list of phone numbers which are formatted in multiple ways such as: (212)-555-1234 or 212-555-1234 or 2125551234.

Using JavaScript, what would be the best way to extract only the area code out of these strings?

like image 311
Gershon Herczeg Avatar asked Oct 24 '25 15:10

Gershon Herczeg


1 Answers

First, remove everything that is not a digit to get the plain number. Then, get the first three digits via slicing:

return myString.replace(/\D/g,'').substr(0, 3);
like image 179
Bergi Avatar answered Oct 27 '25 04:10

Bergi