Last active
December 30, 2018 01:31
-
-
Save morficus/0912c3a9f392b4cc763cfb0c6b5689c6 to your computer and use it in GitHub Desktop.
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
import isEmpty from 'lodash/isEmpty' | |
import isNumber from 'lodash/isNumber' | |
import isNan from 'lodash/isNaN' | |
/** | |
* Extracts digits from given string and formats it as a typical 10-digital US phone number with dashes (###-###-####) | |
* | |
* @param {String} dirtyNumber Any input string | |
* @returns {String} The formatted number | |
*/ | |
export function formatPhoneNumber(dirtyNumber) { | |
if ((isEmpty(dirtyNumber) && !isNumber(dirtyNumber)) || isNan(dirtyNumber)) { | |
return '' | |
} | |
const cleanValue = digitsFromString(dirtyNumber) | |
let formattedValue | |
const first = cleanValue.substring(0, 3) | |
const second = cleanValue.substring(3, 6) | |
const third = cleanValue.substring(6) | |
if (cleanValue.length <= 3) { | |
formattedValue = cleanValue | |
} else if (third) { | |
formattedValue = `${first}-${second}-${third}` | |
} else if (second) { | |
formattedValue = `${first}-${second}` | |
} else if (first) { | |
formattedValue = first | |
} | |
return formattedValue | |
} | |
export function digitsFromString(dirtyNumber) { | |
if (isEmpty(dirtyNumber) && !isNumber(dirtyNumber)) { | |
return '' | |
} | |
if (isNumber(dirtyNumber)) { | |
// if it's a number... return it as a string | |
return String(dirtyNumber) | |
} | |
const digits = dirtyNumber.match(/\d+/g) | |
let returnValue = dirtyNumber | |
if (digits) { | |
returnValue = digits.map(String).join('') | |
} | |
return returnValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment