i18nify-JS
A one-stop solution built in javascript to provide internationalization support.
Hey, dive into this JavaScript toolkitโit's like having a magic kit for your app! ๐ชโจ Picture this: modules for phoneNumber, currency, dateโthey're like enchanted tools that make your app talk fluently in any language, anywhere! It's your ticket to making your app a global citizen, no matter where it goes!
And hey, hang tightโI'll break down each of these enchanting modules in the sections coming up! ๐๐ฑ๐ธ๐๏ธ
Install
yarn add @razorpay/i18nify-js
Local Setup / Want to Contribute ?
Here's your roadmap to getting this party started:
- First things first, clone this treasure trove of code (repository).
- Once you've done that, make sure all the buddies (dependencies) are in place by hitting
yarn install
- You are good to go, go ahead find issues and raise your PR to fix those. Happy coding!!
- To create a build run following command:
yarn build
Go on, code conqueror, the adventure awaits!
Modules
Core Module
Welcome to the command center for your i18n experience! This module serves as the control hub, housing the essential functions to manage your i18n settings seamlessly. This module offers a trio of functions to handle all your i18n needs. Whether it's checking the current state, customizing settings, or starting afresh, this module has got you covered in managing your i18n world! ๐
Functions
setState(newState: Partial <I18nState>
): Customize and update your i18n state with ease! Whether you're changing locales or tweaking directions, this function is your ticket to tailor your i18n experience precisely how you want it! ๐จ
import { setState } from "@razorpay/i18nify-js/core";
// Set a new locale
setState({ locale: 'en-US' });
getState(): Peek into the current i18n state - the active locale, direction, and country settings - at any time, giving you a snapshot of your i18n setup! ๐ธ
import { getState } from '@razorpay/i18nify-js/core';
// Get the current state
const currentState = getState();
console.log(currentState);
/*
{
locale: 'en-US',
direction: '',
country: '',
}
*/
resetState(): Made a mess? No worries! Hit the reset button with this function. It's the ultimate undo for your i18n adjustments, whisking your settings back to their pristine defaults. Fresh start, anyone? ๐
import { resetState } from "@razorpay/i18nify-js/core";
// Reset everything!
resetState();
Module 01: Currency
This module's your go-to guru for everything currency/number-related. ๐ค It's all about formatting, validations, and handy tricks to make dealing with money/numbers a breeze. Here are the cool APIs and utilities this Currency Module gives you to play with! ๐๐ธ
convertToMajorUnit(amount, options)
๐ต๐ This function is your go-to tool for scaling currency values from lower to major units. Just input the amount in a minor unit (like cents or pence) along with the currency code, and voilร ! You get the amount in a major unit (like dollars or pounds). And if you stumble upon an unsupported currency code, it'll promptly let you know by throwing an error.
Examples
console.log(convertToMajorUnit(10000, { currency: 'USD' }));
console.log(convertToMajorUnit(5000, { currency: 'GBP' }));
convertToMinorUnit(amount, options)
๐ต๐ This function is your go-to tool for scaling currency values from higher to minor units. Just input the amount in a major unit (like dollars or pounds) along with the currency code, and voilร ! You get the amount in a minor unit (like cents or pence). And if you stumble upon an unsupported currency code, it'll promptly let you know by throwing an error.
Examples
console.log(convertToMinorUnit(100, { currency: 'USD' }));
console.log(convertToMinorUnit(50, { currency: 'GBP' }));
formatNumber(amount, options)
๐ฉโจ This little wizard helps you jazz up numerical values in all sorts of fancy ways. And guess what? It uses the Internationalization API (Intl) to sprinkle that magic dust and give you snazzy, locale-specific number formatsโespecially for currencies! ๐๐ธ
Examples
console.log(formatNumber('1000.5', { currency: 'USD' }));
console.log(
formatNumber('1500', {
currency: 'EUR',
locale: 'fr-FR',
intlOptions: {
currencyDisplay: 'code',
},
}),
);
console.log(
formatNumber('5000', {
currency: 'JPY',
intlOptions: {
currencyDisplay: 'narrowSymbol',
},
}),
);
getCurrencyList()
๐๐ฐ It's your easy-peasy way to snag a whole list of currencies with their symbols and names. Simple, straightforward, and totally handy!
Examples
console.log(getCurrencyList());
getCurrencySymbol(currencyCode)
Picture this: it's like having a cool decoder ring for currency codes! ๐๐ฐ This little guy, grabs the symbol for a currency code from its secret stash.
Examples
console.log(getCurrencySymbol('USD'));
console.log(getCurrencySymbol('UZS'));
console.log(getCurrencySymbol('OMR'));
formatNumberByParts(amount, options)
This slick function breaks down numbers into separate pieces using Intl.NumberFormat. It's like taking apart a puzzle ๐งฉ โ currency symbol here, integers there, decimals in their placeโwith a fail-proof system to handle any formatting hiccups ๐ฅด along the way. Smooth operator, right?
Examples
console.log(
formatNumberByParts(12345.67, {
currency: 'USD',
locale: 'en-US',
}),
);
console.log(
formatNumberByParts(12345.67, {
currency: 'XYZ',
locale: 'en-US',
}),
);
console.log(
formatNumberByParts(12345.67, {
currency: 'EUR',
locale: 'fr-FR',
}),
);
console.log(
formatNumberByParts(12345.67, {
currency: 'JPY',
locale: 'ja-JP',
}),
);
console.log(
formatNumberByParts(12345.67, {
currency: 'OMR',
locale: 'ar-OM',
}),
);
Module 02: Phone Number
This module's your phone's best friend, handling all things phone number-related. ๐ฑ It's the go-to for formatting, checking if those digits are legit, and all those handy phone-related tricks. And guess what? It's got a bunch of cool stuffโAPIs and utilitiesโjust waiting for you to dive in and make your phone game strong! ๐๐ข
isValidPhoneNumber(phoneNumber, countryCode)
๐ It's like the phone number detective, using fancy patterns to check if a number is the real deal for a specific country code. So, it's pretty simple: if it says true, your number's good to go for that country; if it's false, time to double-check those digits! ๐ต๏ธโโ๏ธ๐
Examples
console.log(isValidPhoneNumber('+14155552671'));
console.log(isValidPhoneNumber('0501234567', 'AE'));
console.log(isValidPhoneNumber('+447700900123'));
console.log(isValidPhoneNumber('123456789', 'US'));
console.log(isValidPhoneNumber('+123456789'));
console.log(isValidPhoneNumber(''));
console.log(isValidPhoneNumber('(555) 555-5555'));
formatPhoneNumber(phoneNumber, countryCode)
๐ It's like your personal phone number stylist, working its magic to make those digits look all snazzy. You can tell it the country code, or it'll figure it out itselfโthen presto! It hands you back a phone number looking sharp and dapper in that country's typical style. โจ๐
Examples
console.log(formatPhoneNumber('+14155552671'));
console.log(formatPhoneNumber('0501234567', 'AE'));
console.log(formatPhoneNumber('+447700900123'));
console.log(formatPhoneNumber('123456789', 'US'));
console.log(formatPhoneNumber('+123456789'));
console.log(formatPhoneNumber(''));
console.log(formatPhoneNumber('(555) 555-5555'));
parsePhoneNumber(phoneNumber, country)
๐ต๏ธโโ๏ธ๐ This clever function digs deep into a phone number, pulling out all the juicy details: country code, dial code, the number all dolled up, and even the format it follows. What's cool? It hands you back an object filled with all these deets, making it a breeze to access everything about that phone number. It's like having the ultimate phone number cheat sheet! ๐
Examples
const phoneNumber = '+1 (555) 123-4567';
const parsedInfo = parsePhoneNumber(phoneNumber);
console.log('Country Code:', parsedInfo.countryCode);
console.log('Formatted Number:', parsedInfo.formattedPhoneNumber);
console.log('Dial Code:', parsedInfo.dialCode);
console.log('Format Template:', parsedInfo.formatTemplate);
const phoneNumber = '987654321';
const countryCode = 'IN';
const parsedInfo = parsePhoneNumber(phoneNumber, countryCode);
console.log('Country Code:', parsedInfo.countryCode);
console.log('Formatted Number:', parsedInfo.formattedPhoneNumber);
console.log('Dial Code:', parsedInfo.dialCode);
('');
console.log('Format Template:', parsedInfo.formatTemplate);
('xxxx xxxxxx');
try {
const invalidPhoneNumber = '';
const parsedInfo = parsePhoneNumber(invalidPhoneNumber);
console.log('Country Code:', parsedInfo.countryCode);
console.log('Formatted Number:', parsedInfo.formattedPhoneNumber);
} catch (error) {
console.error('Error:', error.message);
}
const countryCode = 'JP';
const parsedInfo = parsePhoneNumber('', countryCode);
console.log('Country Code:', parsedInfo.countryCode);
console.log('Format Template:', parsedInfo.formatTemplate);
getDialCodes()
๐๐ข This function is a comprehensive directory of international dial codes, mapped to their respective country codes. Whether you're coding a global application or just need to reference international dialing formats, this function provides a quick and accurate reference, organizing the world's dial codes in a clean, easy-to-use format.
Examples
console.log(getDialCodes());
getDialCodeByCountryCode(countryCode)
๐๐บ๏ธ This function is your quick access to finding the dial code for any specific country, utilizing the country's ISO code. Perfect for applications that require validating user input for phone numbers or enhancing UIs with country-specific details. It ensures you get the exact dial code you need, and if the country code doesn't match, it alerts you right away with an error.
Examples
console.log(getDialCodeByCountryCode('BR'));
console.log(getDialCodeByCountryCode('DE'));
getMaskedPhoneNumber(options)
๐๐ The getMaskedPhoneNumber function is a versatile tool designed to handle phone number formatting and masking based on the specific requirements of different countries. This function is ideal for applications that require the display of partially hidden phone numbers for security purposes or privacy concerns. It supports a wide range of configurations, including options to mask portions of the phone number, specify the number of digits to mask, and choose whether to mask digits from the beginning or end of the number.
Examples
console.log(
getMaskedPhoneNumber({
countryCode: 'US',
phoneNumber: '2025550125',
withDialCode: true,
}),
);
console.log(
getMaskedPhoneNumber({
countryCode: 'IN',
phoneNumber: '9876543210',
maskingOptions: {
maskingStyle: 'suffix',
maskedDigitsCount: 6,
maskingChar: '*',
},
withDialCode: true,
}),
);
console.log(
getMaskedPhoneNumber({
countryCode: 'IN',
phoneNumber: '9876543210',
maskingOptions: {
maskingStyle: 'prefix',
maskedDigitsCount: 6,
maskingChar: '*',
},
withDialCode: true,
}),
);
console.log(
getMaskedPhoneNumber({
countryCode: 'IN',
phoneNumber: '9876543210',
maskingOptions: {
maskingStyle: 'full',
maskingChar: '*',
},
withDialCode: true,
}),
);
console.log(
getMaskedPhoneNumber({
countryCode: 'IN',
phoneNumber: '9876543210',
maskingOptions: {
maskingStyle: 'alternate',
maskingChar: '*',
},
withDialCode: true,
}),
);
console.log(
getMaskedPhoneNumber({
countryCode: 'BR',
}),
);
Module 03: Geo Module ๐
Dive into the digital atlas with the Geo Module ๐, your ultimate toolkit for accessing geo contextual data from around the globe ๐. Whether you're infusing your projects with national pride ๐ or exploring different countries ๐ค, this module is like a magic carpet ride ๐งโโ๏ธ. With a range of functions at your disposal โจ, incorporating global data ๐ฉ into your app has never been easier. Let's explore these global gems ๐:
The Geo Module is designed to enrich your applications by providing easy access to high-quality flag images and emojis, country information, states, cities, and zip codes for every country.
Note: Below APIs in the Geo module currently support a limited set of countries.
- getStates
- getCities
- getZipcodes
These countries are 'IN', 'MY', 'SG' and 'US'.
getAllCountries
Looking for a global adventure? The getAllCountries API is your passport to a world of fun facts! Get ready to explore every country on the map, complete with cool details like names, languages, currencies, dial codes, and even their snazzy flags.
Examples
const res = await getAllCountries();
console.log(res);
getStates(country_code)
Embark on a state-by-state discovery with the getStates API! Get access to a treasure trove of state information, including names, time zones, and even a list of vibrant cities within each state.
Examples
const res = await getStates('IN');
console.log(res);
getStates('XYZ').catch((err) => {
console.log(err);
});
getCities(country_code, states_code)
Uncover the charm of cities worldwide with the getCities API! This dynamic tool fetches an array of cities complete with their names, time zones, and region names, providing a detailed glimpse into urban life across the globe.
Examples
const res = await getCities('IN');
console.log(res);
const res = await getCities('IN', 'DL');
console.log(res);
getCities('XYZ').catch((err) => {
console.log(err);
});
getCities('IN', 'XYZ').catch((err) => {
console.log(err);
});
getZipcodes(country_code, states_code)
Explore postal codes with the getZipcodes API! Discover a list of unique zip codes organized by country and state, making it easy to navigate geographic areas and streamline address-based operations.
Examples
const res = await getZipcodes('IN');
console.log(res);
const res = await getZipcodes('IN', 'DL');
console.log(res);
getZipcodes('XYZ').catch((err) => {
console.log(err);
});
getZipcodes('IN', 'XYZ').catch((err) => {
console.log(err);
});
getFlagOfCountry(countryCode) ๐
Source for flag images: FlagCDN.
Retrieve flag images for any ISO country code ๐โ๏ธ with a simple API call, bolstering your application's global engagement ๐ and honoring worldwide diversity ๐ณ๏ธ. This method efficiently integrates international flags into your digital projects, leveraging high-resolution SVG formats from a reliable source.
Examples
console.log(getFlagOfCountry('US'));
console.log(getFlagOfCountry('IN'));
try {
console.log(getFlagOfCountry('XX'));
} catch (error) {
console.error(error.message);
}
getFlagsForAllCountries() ๐
Source for flag images: FlagCDN.
Access a comprehensive collection of global flags with an ISO country code ๐โ๏ธโserving as your digital passport ๐ to a visually unified world. This feature amplifies your app's international flair ๐ and celebrates cultural diversity ๐ณ๏ธ๐ by embedding flags from every recognized nation.
Examples
const allFlags = getFlagsForAllCountries();
console.log(allFlags);
Module 04: Date & Time Module
This module provides functions for formatting and manipulating dates and times in a locale-sensitive manner using the JavaScript Intl API & Date object.
formatDateTime(date, options)
๐ ๏ธ Dive into the sophistication of formatDateTime, a highly configurable function designed for developers seeking to master the intricacies of international date and time formatting. Leveraging the robust capabilities of the Intl.DateTimeFormat API, this utility offers unparalleled precision and adaptability in crafting date-time strings. Whether your application caters to a global audience or requires meticulous timestamping, formatDateTime delivers the versatility and accuracy essential for modern software development. ๐๐ง
Examples
console.log(
formatDateTime('2024-12-31 23:59', {
locale: 'en-US',
dateTimeMode: 'dateTime',
intlOptions: {
weekday: 'long',
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
},
}),
);
console.log(
formatDateTime('2024-05-20', {
locale: 'ja-JP',
dateTimeMode: 'dateOnly',
}),
);
console.log(
formatDateTime('2024-05-20 15:45:30', {
locale: 'fr-FR',
dateTimeMode: 'timeOnly',
intlOptions: {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true,
},
}),
);
Utilize formatDateTime
to ensure your application's date and time outputs are not only accurate ๐ฏ but also culturally and contextually appropriate ๐. From backend logging systems ๐ฅ๏ธ to user-facing interfaces ๐ฑ, this function stands as a testament to your commitment to internationalization ๐ and user experience excellence โจ. With its straightforward implementation ๐ ๏ธ and extensive configuration options โ๏ธ, formatDateTime
empowers you to meet the diverse needs of your audience ๐ฅ, promoting clarity ๐ and understanding ๐ค across different cultures and languages ๐ฃ๏ธ.
getRelativeTime(date, options)
โณ๐ This time-traveling virtuoso effortlessly bridges the gap between dates, offering a glimpse into the past or a peek into the future. With the help of the Internationalization API (Intl), getRelativeTime
transforms absolute dates into relatable, human-friendly phrases like '3 hours ago' or 'in 2 days'. Whether you're reminiscing the past or anticipating the future, this function keeps you connected to time in the most intuitive way! ๐๐ฐ๏ธ
Examples
console.log(getRelativeTime('2024-01-20'));
console.log(getRelativeTime('2024-01-26'));
console.log(
getRelativeTime('2024-01-26', { locale: 'fr-FR', baseDate: '2024-01-23' }),
);
๐ก Pro Tip: getRelativeTime
is not just a way to express time differences; it's a bridge that connects your users to the temporal context in a way that's both meaningful and culturally aware. Time is more than seconds and minutes; it's a story, and this function helps you tell it! ๐โ
getWeekdays(options)
๐
๐ This global day-namer is your trusty guide through the week, no matter where you are in the world. Using the power of the Internationalization API (Intl), getWeekdays
serves up the names of all seven days tailored to your chosen locale. From planning international meetings to creating a multilingual planner, this function provides the perfect blend of cultural awareness and practical utility, keeping you in sync with the local rhythm of life, one day at a time! ๐๐๏ธ
Examples
console.log(getWeekdays({ locale: 'en-US' }));
console.log(getWeekdays({ locale: 'fr-FR' }));
console.log(getWeekdays({ locale: 'ja-JP' }));
๐ก Did You Know? The order and names of weekdays vary across cultures and languages. With getWeekdays
, you can easily cater to a global audience, ensuring that your application speaks their language, quite literally! ๐๐ฃ๏ธ
parseDateTime(dateInput, options)
๐๐๏ธ The parseDateTime
function is like a time-traveler's best friend, expertly navigating the complex world of dates and times. Whether it's a string or a Date object you're dealing with, this function seamlessly transforms it into a comprehensive, easy-to-digest package of date information, tailored to any locale you desire. ๐โฒ๏ธ
Examples
const parsed1 = parseDateTime('18/01/2024');
console.log(parsed1);
const parsed2 = parseDateTime('2024-01-23', {
intlOptions: {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
},
locale: 'fr-FR',
});
console.log(parsed2);
const parsed3 = parseDateTime(new Date(2024, 0, 23));
console.log(parsed3);
๐ก Pro Tip: Leverage parseDateTime
in applications where detailed date analysis and manipulation are key, such as in calendar apps, scheduling tools, or date-sensitive data processing. It's like having a Swiss Army knife for all things related to dates and times! ๐
๐ ๏ธ
Calendar, CalendarDate, CalendarDateTime, Time, ZonedDateTime
Leverage the power of Adobe's @internationalized/date with our module, designed to offer a sophisticated, locale-sensitive approach to managing dates and times. Utilize these advanced tools to create applications that are both intuitive and efficient, ensuring they connect with users worldwide.
Discover more about integrating these powerful components into your software at Adobe's Internationalized Date Documentation.
Tailor your app with comprehensive calendar interfaces, ensuring global locale compatibility.
Focus on date-specific functionalities, perfect for event planning and deadlines without the time zone hassle.
Merge dates and times seamlessly for scheduling and reminders, with smart time zone handling.
Simplify time tracking and events in your app, concentrating solely on time without the date aspect.
Master global time zones for scheduling and planning across borders, ensuring accuracy and user relevance.