forked from xola/ui-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
X2-7706 feat(helpers): adds
formatPhoneNumber
helper function
- Loading branch information
1 parent
5a0e0cc
commit 0b88646
Showing
3 changed files
with
58 additions
and
39 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import phoneLib from "google-libphonenumber"; | ||
|
||
const PNF = phoneLib.PhoneNumberFormat; | ||
const phoneUtil = phoneLib.PhoneNumberUtil.getInstance(); | ||
|
||
export const getRegionCode = (number, countryCode = "US") => { | ||
let phoneObject = phoneUtil.parseAndKeepRawInput(number, countryCode); | ||
|
||
return phoneUtil.getRegionCodeForNumber(phoneObject); | ||
}; | ||
|
||
/** | ||
* Formats the Phone Number for provided country code | ||
* | ||
* @param number {string} | ||
* @param countryCode {string} | ||
* | ||
* @return {string} | ||
*/ | ||
export const formatPhoneNumber = (number, countryCode = "US") => { | ||
try { | ||
let phoneObject = phoneUtil.parseAndKeepRawInput(number, countryCode); | ||
|
||
const regionCode = phoneUtil.getRegionCodeForNumber(phoneObject); | ||
if (regionCode && regionCode !== countryCode) { | ||
// If the region code is different than what was passed in, reparse according to that format | ||
phoneObject = phoneUtil.parseAndKeepRawInput(number, regionCode); | ||
} | ||
|
||
// Parse number for display in the region's format | ||
let formattedNumber; | ||
|
||
if (regionCode) { | ||
const format = regionCode === countryCode ? PNF.NATIONAL : PNF.INTERNATIONAL; | ||
formattedNumber = phoneUtil.format(phoneObject, format); | ||
} else { | ||
// If we didn't detect a region, don't guess and return the original thing | ||
formattedNumber = number; | ||
} | ||
|
||
return formattedNumber; | ||
} catch { | ||
return number; | ||
} | ||
}; |
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