libphonenumber-js

1.12.41 · active · verified Sun Apr 19

libphonenumber-js is a JavaScript and TypeScript library designed for parsing, formatting, and validating international phone numbers. It serves as a significantly smaller and simpler rewrite of Google's original `libphonenumber` library. Currently at version 1.12.41, this package prioritizes a reduced bundle size (approximately 145 kB vs. 550 kB for the Google port) by focusing solely on personal phone numbers. It deliberately omits support for less common categories such as emergency numbers, short codes, numbers prefixed with `*`, Australian `13`-smart numbers, and alphabetic phone numbers like `1-800-GOT-MILK`. The library ships with comprehensive TypeScript definitions and uniquely offers functionality to search for phone numbers within text, a feature absent in Google's official JavaScript port. While a specific release cadence isn't detailed, the version history suggests active and ongoing development.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing, formatting, and validating phone numbers, including checking country-specific validity and retrieving calling codes.

import { parsePhoneNumber, formatPhoneNumber, isValidPhoneNumber, getCountryCallingCode } from 'libphonenumber-js';

const phoneNumberString = '+12133734253';
const countryCode = 'US';

// Parse a phone number
const phoneNumber = parsePhoneNumber(phoneNumberString);

if (phoneNumber) {
  console.log(`Original number: ${phoneNumberString}`);
  console.log(`Country: ${phoneNumber.country}`);
  console.log(`National number: ${phoneNumber.nationalNumber}`);

  // Format the number in various ways
  console.log(`Formatted E.164: ${phoneNumber.format('E.164')}`);
  console.log(`Formatted International: ${phoneNumber.format('INTERNATIONAL')}`);
  console.log(`Formatted National: ${phoneNumber.format('NATIONAL')}`);

  // Check validity
  const valid = isValidPhoneNumber(phoneNumberString, countryCode);
  console.log(`Is valid for ${countryCode}? ${valid}`);

  // Get country calling code
  const callingCode = getCountryCallingCode(countryCode);
  console.log(`Calling code for ${countryCode}: +${callingCode}`);

} else {
  console.log(`Could not parse phone number: ${phoneNumberString}`);
}

// Example of an invalid number
const invalidNumber = '555-123-INVALID';
const isValid = isValidPhoneNumber(invalidNumber, countryCode);
console.log(`Is '${invalidNumber}' valid for ${countryCode}? ${isValid}`);

view raw JSON →