Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Last active April 23, 2021 19:14
Show Gist options
  • Save kevinweber/1249fde7b3d26fe73e1be0d52d3c023a to your computer and use it in GitHub Desktop.
Save kevinweber/1249fde7b3d26fe73e1be0d52d3c023a to your computer and use it in GitHub Desktop.
Convert string to match E.164 phone number pattern (e.g. +1234567890)
/**
* 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;
}
@josephpaulmckenzie
Copy link

josephpaulmckenzie commented Jul 18, 2018

First let me say thanks this almost worked for me however it would add an + sign even there was no 1 in the phone number. Here is a simple update to your function to check for a 1 for the first number and if not there add it too.

if (newString[0].includes('1')) { newString = '+' + newString; } else { newString = '+1' + newString; }

add it before line 18

@Sven-Q
Copy link

Sven-Q commented Sep 27, 2018

First let me say thanks this almost worked for me however it would add an + sign even there was no 1 in the phone number. Here is a simple update to your function to check for a 1 for the first number and if not there add it too.

if (newString[0].includes('1')) { newString = '+' + newString; } else { newString = '+1' + newString; }

add it before line 18

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment