Skip to content

Instantly share code, notes, and snippets.

@mnoble01
Last active March 2, 2023 14:03
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mnoble01/8365987 to your computer and use it in GitHub Desktop.
Save mnoble01/8365987 to your computer and use it in GitHub Desktop.
i18n libphonenumber mask (with in-hand country code)
/*
This is using the JS port of Google's libphonenumber.
As far as I know, though, all of the APIs are the same or similar
*/
// I just hardcoded "US" as the country, but of course you can use any country iso code
var ctry = 'US';
var exampleNumber = i18n.phonenumbers.PhoneNumberUtil.getInstance()
.getExampleNumberForType(ctry, i18n.phonenumbers.PhoneNumberType.MOBILE); // returns PhoneNumber instance
exampleNumber.values_ // I believe the trailing underscore means this is undocumented... but I like to live dangerously
// Well, I also haven't unearthed an API call to actually get the number text, or to format a number from a PhoneNumber instance
// I know the AsYouTypeFormatter would do it, but you have to enter one character at a time
// Returns an object {1: <countryCode>, 2: <phoneNumber>}, both are Numbers
// Can use any of the provided formatting fns here
// Example output: "+1 201-555-5555"
var formattedNumber = formatNumberForMobileDialing(ctry, exampleNumber.values_[2].toString());
// You may also want to L18n the placeholder character, but I haven't looked into what's expected in other languages
// Example output: "+x xxx-xxx-xxxx"
var mask = formattedNumber.replace(/\d/g, 'x');
@mnoble01
Copy link
Author

I ended up not using this, and so looked no further into cleaning this up. I really just wanted to know I could.

@agustinhaller
Copy link

Great idea, I used it for my Angular 2/Ionic app. Thanks!

@Vingtoft
Copy link

I used this as well, still works, thanks for the inspiration!!

@Vakil-Parth
Copy link

awesome

@abdelgrib
Copy link

'_' means private field :)

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