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?
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?
Share Improve this question edited Dec 13, 2012 at 20:43 Ashley Strout 6,2586 gold badges27 silver badges48 bronze badges asked Dec 13, 2012 at 20:41 Gershon HerczegGershon Herczeg 3,05425 silver badges33 bronze badges 2- 1 Need some more context about the data in which the phone numbers are found. Is it one phone number per line? Are the phone numbers embedded in text? Could there be multiple phone numbers on a single line? Maybe you could include an example of the raw data from which you're trying to extract the area codes. – David Commented Dec 13, 2012 at 20:45
- Answers below answered my question, I wish i could accept all the correct ones :) – Gershon Herczeg Commented Dec 13, 2012 at 20:50
5 Answers
Reset to default 8First, 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);
Get the first 3 consecutive digits...
/[0-9]{3}/.exec("(212)-555-1234")[0]
Sample (fiddle):
console.log(/[0-9]{3}/.exec("(212)-555-1234")[0]); // 212
console.log(/[0-9]{3}/.exec("212-555-1234")[0]); // 212
console.log(/[0-9]{3}/.exec("2125551234")[0]); // 212
You can also use my library.
https://github.com/Gilshallem/phoneparser
Example
parsePhone("12025550104");
result: { countryCode:1, areaCode:202, number:5550104, countryISOCode:"US" }
Take the first 3 digits of a 10 digit number, or the first 3 digits after the 1 of an 11 digit number starting with 1. This assumes your domain is U.S. phone numbers.
Regex as '^\(*(\d{3})'
should do it. Get the first group from the match.
Here ^
will start the match from beginning, \d{3}
will match 3 digits. \(*
will match the optional starting parenthesis. You don't need to care about next digit or symbols after the area code.