Last active
August 18, 2017 05:49
-
-
Save shaunwallace/c5ab578edeed792c3611d57c24aea422 to your computer and use it in GitHub Desktop.
Telephone formatter
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
| // eg (123) 456-7890 | |
| formatter(s) { | |
| // strip out all formatting that exists on the string | |
| const tel = s.replace(/[(\-)\s]/g, ''); | |
| // if there is nothing after sanitizing or non-numeric characters | |
| // were entered then simply return the current state | |
| if (!tel) { | |
| return { tel: '' }; | |
| } else if (tel.match(/[^.\d]/g)) { | |
| return this.state; | |
| } | |
| const { length } = tel; | |
| const areaCode = tel.substring(0, 3); | |
| const firstSet = tel.substring(3, 6); | |
| const lastSet = tel.substring(6, 10); | |
| // the below could probably be better included in another regex | |
| // or even better the rules for formatting would come as a schema | |
| // to this function so that formatting can be dynamic, eg international country codes | |
| const openingParen = length && '('; | |
| const closingParen = length > 3 ? ') ' : ''; | |
| const dash = firstSet.length === 3 && lastSet ? '-' : ''; | |
| return { | |
| tel: `${openingParen}${areaCode}${closingParen}${firstSet}${dash}${lastSet}` | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment