Regular Expression to reformat a US phone number in Javascript

后端 未结 13 2295
眼角桃花
眼角桃花 2020-12-02 07:32

I\'m looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here\'s an example of some of the data:

13条回答
  •  孤街浪徒
    2020-12-02 08:32

    For US Phone Numbers

    /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/
    

    Let’s divide this regular expression in smaller fragments to make is easy to understand.

    • /^\(?: Means that the phone number may begin with an optional (.
    • (\d{3}): After the optional ( there must be 3 numeric digits. If the phone number does not have a (, it must start with 3 digits. E.g. (308 or 308.
    • \)?: Means that the phone number can have an optional ) after first 3 digits.
    • [- ]?: Next the phone number can have an optional hyphen (-) after ) if present or after first 3 digits.
    • (\d{3}): Then there must be 3 more numeric digits. E.g (308)-135 or 308-135 or 308135
    • [- ]?: After the second set of 3 digits the phone number can have another optional hyphen (-). E.g (308)-135- or 308-135- or 308135-
    • (\d{4})$/: Finally, the phone number must end with four digits. E.g (308)-135-7895 or 308-135-7895 or 308135-7895 or 3081357895.

      Reference :

    http://www.zparacha.com/phone_number_regex/

提交回复
热议问题