Created
March 31, 2014 11:43
-
-
Save wegorich/9890535 to your computer and use it in GitHub Desktop.
USA phone formating
This file contains 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
format_phone = (phone, convert, trim) -> | |
convert = true if typeof convert is "undefined" | |
trim = true if typeof trim is "undefined" | |
# Strip out any extra characters that we do not need only keep letters and numbers | |
phone = phone.replace(/[^0-9A-Za-z]/, "") | |
# Do we want to convert phone numbers with letters to their number equivalent? | |
if convert is true and phone.match(/[a-zA-Z]/) | |
replace = | |
2: ["a","b","c"] | |
3: ["d","e","f"] | |
4: ["g","h","i"] | |
5: ["j","k","l"] | |
6: ["m","n","o"] | |
7: ["p","q","r", "s"] | |
8: ["t", "u","v"] | |
9: ["w","x","y","z"] | |
# Replace each letter with a number | |
# Notice this is case insensitive with the str_ireplace instead of str_replace | |
for digit of replace | |
regex = new RegExp("[" + replace[digit].join("") + "]", "ig") | |
phone = phone.replace(regex, digit) | |
# If we have a number longer than 11 digits cut the string down to only 11 | |
# This is also only ran if we want to limit only to 11 characters | |
phone = phone.substr(0, 11) if trim is true and phone.length > 11 | |
# Perform phone number formatting here | |
if phone.length is 7 | |
return phone.replace(/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "$1-$2") | |
else if phone.length is 10 | |
return phone.replace(/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "($1) $2-$3") | |
else return phone.replace(/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "$1($2) $3-$4") if phone.length is 11 | |
# Return original phone if not 7, 10 or 11 digits long | |
phone |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment