最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parse area code out of phone number - Stack Overflow

programmeradmin2浏览0评论

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
Add a comment  | 

5 Answers 5

Reset to default 8

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);

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.

发布评论

评论列表(0)

  1. 暂无评论