Last active
April 23, 2021 19:14
-
-
Save kevinweber/1249fde7b3d26fe73e1be0d52d3c023a to your computer and use it in GitHub Desktop.
Convert string to match E.164 phone number pattern (e.g. +1234567890)
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
/** | |
* Convert string to match E.164 phone number pattern (e.g. +1234567890), | |
* otherwise return empty string. | |
*/ | |
function enforcePhoneNumberPattern(string) { | |
let newString = string.match(/[0-9]{0,14}/g); | |
if (newString === null) { | |
return ''; | |
} | |
// Join parts returned from RegEx match | |
newString = newString.join(''); | |
// Start number with "+" | |
newString = '+' + newString; | |
// Limit length to 15 characters | |
newString = newString.substring(0, 15); | |
return newString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A number does not always need to start with "1" to add the +-sign, this just means the country code where "1" means US. So your given solution would only work for the US and all other countries would also suddenly become US.
For example a number 32 (Belgium) --> 32 378542364 would become +132378542364 while it should be +32378542364.