Last active
September 20, 2020 14:05
-
-
Save peyerluk/8357036 to your computer and use it in GitHub Desktop.
Format swiss phone number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# validating samples: | |
# 783268674 | |
# 0783268674 | |
# 0410783268674 | |
# 00410783268674 | |
# +410783268674 | |
# 041783268674 | |
# 0041783268674 | |
# +41783268674 | |
# ++41783268674 | |
# ++41(0)783268674 | |
# (0)783268674 | |
swissPhoneRegex: /^(0041|041|\+41|\+\+41|41)?(0|\(0\))?([1-9]\d{1})(\d{3})(\d{2})(\d{2})$/ | |
# swissPhoneRegex is setup so we can also use it to format valid phone numbers consistently | |
formatPhoneNumber: (phone) -> | |
# regex is set up so we can easily format the matching parts | |
phone = phone.replace(/[\s()]/g, "") | |
res = @swissPhoneRegex.exec(phone) | |
if res then "0#{ res[3] } #{ res[4] } #{ res[5] } #{ res[6] }" else "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have settled on this for the moment:
It's not perfect, and will miss some formatting of phone numbers. However, it's less greedy, works for the formatted numbers that I currently care about and can be used without stripping whitespace.
It works for these test numbers: