Created
January 16, 2023 09:29
-
-
Save CoderNamedHendrick/3c0666f4cbca5302d8ccc34b7861889e to your computer and use it in GitHub Desktop.
An extension on strings to format inputted string to required international format. Currently static and not injectable.
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
extension StringNumberExtension on String { | |
static final zeroFirstDigitRegExp = RegExp('^0'); | |
static final internationalFormatWithPlusFirstDigitsRegExp = | |
RegExp('^[+234]{4}'); | |
static final internationalFormatWithoutPlusFirstDigitsRegExp = | |
RegExp('^[234]{3}'); | |
String toNumberFormat() { | |
if (isEmpty) { | |
return ''; | |
} | |
if (contains(zeroFirstDigitRegExp)) { | |
return replaceFirst(zeroFirstDigitRegExp, '+234'); | |
} | |
if (contains(internationalFormatWithPlusFirstDigitsRegExp)) { | |
return this; | |
} | |
if (contains(internationalFormatWithoutPlusFirstDigitsRegExp)) { | |
return '+$this'; | |
} | |
return '+234$this'; | |
} | |
String toLocalNumberFormat() { | |
if (isEmpty) { | |
return ''; | |
} | |
if (contains(internationalFormatWithPlusFirstDigitsRegExp)) { | |
return replaceFirst(internationalFormatWithPlusFirstDigitsRegExp, '0'); | |
} | |
if (contains(internationalFormatWithoutPlusFirstDigitsRegExp)) { | |
return replaceFirst(internationalFormatWithoutPlusFirstDigitsRegExp, '0'); | |
} | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment