Introduction to libphonenumber-js
libphonenumber-js is a powerful library for parsing, formatting, and validating international phone numbers. It provides a variety of useful APIs to handle phone number operations efficiently. In this article, we will explore numerous API examples along with a sample application to demonstrate the functionality of libphonenumber-js.
1. Parsing Phone Numbers
Use the parsePhoneNumber
method to parse a phone number string into an object containing detailed information.
import { parsePhoneNumber } from 'libphonenumber-js';
const phoneNumber = parsePhoneNumber('+12133734253'); console.log(phoneNumber.country); // US console.log(phoneNumber.number); // +12133734253
2. Formatting Phone Numbers
The format
method helps in formatting a phone number into various international formats.
import { format } from 'libphonenumber-js';
const formattedNumber = format('+12133734253', 'INTERNATIONAL'); console.log(formattedNumber); // +1 213 373 4253
3. Validating Phone Numbers
Validate phone numbers using the isValidNumber
method.
import { isValidNumber } from 'libphonenumber-js';
const isValid = isValidNumber('+12133734253'); console.log(isValid); // true
4. Getting Country from Phone Number
Get the country of the phone number using the getCountryCallingCode
method.
import { getCountryCallingCode } from 'libphonenumber-js';
const countryCode = getCountryCallingCode('US'); console.log(countryCode); // 1
5. Detecting Number Type
Determine the type of phone number using the getType
method.
import { getType } from 'libphonenumber-js';
const numberType = getType('+12133734253'); console.log(numberType); // 'FIXED_LINE_OR_MOBILE'
Sample Application
Below is a sample application that demonstrates the usage of various libphonenumber-js APIs.
import { parsePhoneNumber, format, isValidNumber, getCountryCallingCode, getType } from 'libphonenumber-js';
const phoneNumber = '+12133734253';
const parsedNumber = parsePhoneNumber(phoneNumber); console.log('Parsed Number:', parsedNumber);
const formattedNumber = format(phoneNumber, 'INTERNATIONAL'); console.log('Formatted Number:', formattedNumber);
const isValid = isValidNumber(phoneNumber); console.log('Is Valid:', isValid);
const countryCode = getCountryCallingCode(parsedNumber.country); console.log('Country Code:', countryCode);
const numberType = getType(phoneNumber); console.log('Number Type:', numberType);
In this sample application, we parse a phone number, format it, verify its validity, fetch the country calling code, and determine the number type using various methods provided by the libphonenumber-js library.
Hash: fa240cb5281f7bc7b60d8a5f73039c4b75af739ab8ac9c7f98de7df65a0fd8af