https://github.com/persian-tools/persian-tools
An anthology of a variety of tools for the Persian language in javascript
https://github.com/persian-tools/persian-tools
card-number code-melli code-melli-validator convert-numbers convert-persian-number english-number-to-persian fuzzy-matching iban iranian-national-id number-to-words persian-characters persian-language persian-words-to-number remove-commas sheba sheba-validator verify-bank-nunber verify-national-id words-to-numbers
Last synced: about 1 year ago
JSON representation
An anthology of a variety of tools for the Persian language in javascript
- Host: GitHub
- URL: https://github.com/persian-tools/persian-tools
- Owner: persian-tools
- License: mit
- Created: 2018-06-18T10:00:57.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2025-05-12T19:05:41.000Z (about 1 year ago)
- Last Synced: 2025-05-12T20:27:15.926Z (about 1 year ago)
- Topics: card-number, code-melli, code-melli-validator, convert-numbers, convert-persian-number, english-number-to-persian, fuzzy-matching, iban, iranian-national-id, number-to-words, persian-characters, persian-language, persian-words-to-number, remove-commas, sheba, sheba-validator, verify-bank-nunber, verify-national-id, words-to-numbers
- Language: TypeScript
- Homepage: http://persian-tools.js.org/
- Size: 4.76 MB
- Stars: 1,118
- Watchers: 12
- Forks: 122
- Open Issues: 31
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
- Security: SECURITY.md
Awesome Lists containing this project
README
Persian tools
A standalone, library-agnostic JavaScript utility for Persian language features.

[](https://codecov.io/gh/persian-tools/persian-tools)
[](https://github.com/persian-tools/persian-tools/blob/master/LICENSE)
[](https://github.com/persian-tools/persian-tools/compare)
[](https://www.codefactor.io/repository/github/persian-tools/persian-tools)

## Features
- [Convert Persian words to the number](#convert-persian-words-to-the-number).
- [Convert Numbers to Persian words](#convert-numbers-to-persian-words).
- [Add and remove commas to numbers](#add-and-remove-commas).
- [Convert Persian numbers to Arabic or English numbers and vice versa](#convert-persian-numbers-to-arabic-or-english-numbers-and-vice-versa).
- [Validate Iranian national number(code-e Melli)](#validate-iranian-national-numbercode-e-melli).
- [Validate Iranian legal id(shenase hoghoghi)](#validate-iranian-legal-idshenase-hoghoghi).
- [Find city and province name by national code(code-e Melli)](#find-city-and-province-name-by-national-idcode-e-melli).
- [Bill calculator](#bill-calculator).
- [Check Iranian Sheba(IBAN) validation and recognize bank information by sheba code](#iranian-shebaiban).
- [Validate Bank card number](#bank-number-validation-and-get-the-name-of-the-bank-by-bank-account-number).
- [Find Bank's name by Card number](#bank-number-validation-and-get-the-name-of-the-bank-by-bank-account-number).
- [Validate the correctness of the text of the Persian language and clear the Arabic letters in the Persian text](#validate-the-correctness-of-the-text-of-the-persian-language-and-clear-the-arabic-letters-in-the-persian-text).
- [Fix Persian characters in URL](#fix-persian-characters-in-url).
- [Fix Persian zero-width non-joiner(Replace spaces by half-space)](#fix-persian-zero-width-non-joinerreplace-spaces-by-half-space)
- [Convert Jalaali date-time into a time ago](#convert-jalaali-date-time-into-a-time-ago)
- [Get the Remaining Time of the Date](#get-the-remaining-time-of-the-date)
- [Validate and find information of phone number](#validate-and-find-information-of-phone-number).
- [Find capital city by province name ](#find-capital-city-by-province-name)
- [Find province from coordinate ](#find-province-from-coordinate)
## Getting started
There are two main ways to get PersianTools.js in your JavaScript project:
via script tags or by installing it from NPM
and using a build tool like Parcel,
WebPack, or Rollup.
### via Script Tag
Add the following code to an HTML file:
```html
// Notice there is no 'import' statement. 'all persian-tools functions like digitsEnToFa, etc...' is available on the index-page
// because of the script tag above.
// Takes a string made of English digits only, and returns a string that represents the same number but with Persian digits
var convertToFa = PersianTools.digitsEnToFa(1234567);
// etc...
```
Open up that html file in your browser, and the code should run!
### Install
Install the PersianTools to your project using yarn or npm. Note: Because
we use ES2017 syntax (such as `import`), this workflow assumes you are using a modern browser, or a bundler/transpiler
to convert your code to something older browsers understand.
```bash
$ npm install --save @persian-tools/persian-tools
```
or
```bash
$ yarn add @persian-tools/persian-tools
```
### Simple usage
```javascript
import * as persianTools from "@persian-tools/persian-tools";
// or
import { digitsEnToFa } from "@persian-tools/persian-tools";
// Takes a string made of English digits only, and returns a string that represents the same number but with Persian digits
const convertedToFa = persianTools.digitsEnToFa(1234567);
// or
const convertedToFa = digitsEnToFa(1234567);
```
## Usage
Let's take a look at what an example test case would look like using Persian-tools.
### Convert Persian words to the number
| Options | Description | Default |
| ------------------------------------------ | ----------------------------------------------------------------------------------- | ------- |
| `fuzzy`**(Beta)** | Fix typo in the Persian words by using **levenshtein** algorithm | `false` |
| `digits` | Result will be converted to the English or Persian digits | `en` |
| `addCommas` | Commas will be added to the Result | `false` |
| `autoConvertDigitsToEn`**(New)** | Automatically convert the digits to English digits if the input is a Persian number | `false` |
| `autoConvertArabicCharsToPersian`**(New)** | Automatically convert the Arabic characters to Persian characters | `false` |
- Convert with no option
```javascript
import { wordsToNumber } from "@persian-tools/persian-tools";
wordsToNumber("منفی سه هزارمین"); // -3000
wordsToNumber("منفی سه هزارم"); // -3000
wordsToNumber("منفی سه هزار"); // -3000
wordsToNumber("سه هزار دویست و دوازده"); // 3212
wordsToNumber("دوازده هزار بیست دو"); // 12022
```
- Digits converter
```js
wordsToNumber("منفی سه هزارمین", { digits: "fa" }); // "-۳۰۰۰"
wordsToNumber("دوازده هزار بیست دو", { digits: "fa" }); // ۱۲۰۲۲
```
- Add commas
```js
wordsToNumber("منفی سه هزارمین", { addCommas: true }); // "-3,000"
wordsToNumber("دوازده هزار بیست دو", { addCommas: true }); // "12,022"
```
- Fuzzy typo fixer(`v1.5.0`):
```javascript
import { WordsToNumber } from "@persian-tools/persian-tools";
wordsToNumber("یگصد و بنجاه هزار", { fuzzy: true }); // "150000"
wordsToNumber("دویشت ر بیشت هزار", { fuzzy: true }); // "220000"
wordsToNumber("منقی ضد", { fuzzy: true }); // "-100"
```
### Convert Numbers to Persian words
```javascript
import { numberToWords } from "@persian-tools/persian-tools";
numberToWords(500443); // "پانصد هزار و چهار صد و چهل و سه"
numberToWords("500,443"); // "پانصد هزار و چهار صد و چهل و سه"
numberToWords("500,443", { ordinal: true }); // "پانصد هزار و چهار صد و چهل و سوم"
numberToWords(30000000000); // "سی میلیارد"
```
**NOTE:** This function supports the largest safe integer (9007199254740991 / 2^53 - 1)
### Add and remove commas
```javascript
import { addCommas, removeCommas } from "@persian-tools/persian-tools";
addCommas(30000000); // "30,000,000"
removeCommas("30,000,000"); // 30000000
```
### Convert Persian numbers to Arabic or English numbers and vice versa
```javascript
import {
digitsArToFa,
digitsArToEn,
digitsEnToFa,
digitsFaToEn,
digitsEnToAr,
digitsFaToAr,
} from "@persian-tools/persian-tools";
digitsArToFa("۸۹123۴۵"); // "۸۹123۴۵"
digitsArToEn("٨٩123٤٥"); // "8912345"
digitsEnToFa("123۴۵۶"); // "۱۲۳۴۵۶"
digitsEnToAr("123٤٥٦"); // "۱۲۳٤٥٦"
digitsFaToAr("۱۷۸۲۳۴۰۵۶۹"); // ١٧٨٢٣٤٠٥٦٩
```
### Validate Iranian national number(code-e Melli)
| Options | Description | Default |
| ---------------------- | --------------------------------------------------------------------------------- | ------- |
| `checkPrefix`**(New)** | Whether to check the first 3 digits against a predefined list of valid city codes | `true` |
```javascript
import { verifyIranianNationalId, getPlaceByIranNationalId } from "@persian-tools/persian-tools";
verifyIranianNationalId("0499370899"); // true
verifyIranianNationalId("0684159415"); // false
```
### Validate Iranian legal id(shenase hoghoghi)
```javascript
import { verifyIranianLegalId } from "@persian-tools/persian-tools";
verifyIranianLegalId(10380285692); // false
verifyIranianLegalId(10380284790); // true
```
### Find city and province name by national-id(code-e Melli)
```javascript
getPlaceByIranNationalId("0084575948").city; // "تهران مرکزی"
```
### Bank number validation and get the name of the bank by bank account number
```javascript
import { verifyCardNumber, getBankNameFromCardNumber } from "@persian-tools/persian-tools";
verifyCardNumber(6037701689095443); // true
getBankNameFromCardNumber("6219861034529007"); // "بانک سامان"
```
### Validate the correctness of the text of the Persian language and clear the Arabic letters in the Persian text.
```javascript
import { isPersian, hasPersian, toPersianChars } from "@persian-tools/persian-tools";
isPersian("این یک متن فارسی است؟"); // true
isPersian("Lorem Ipsum Test"); // false
isPersian("هل هذا نص فارسي؟"); // false
hasPersian("This text includes فارسی"); // true
toPersianChars("علي"); // علی
```
**Note**: You can pass `2` more options to `isPersian` to customize it as your needs:
- `isComplex`: If you pass `true`, Then it accepts some of regular arabic characters which are commons in persian texts.(default is `false`)
- `trimPattern`: By default the function skips some of characters e.g. `"'-+()؟.` and `whitespaces`. You can pass your own customized `regex` as you need.
### Fix Persian characters in URL.
```javascript
import { urlFix } from "@persian-tools/persian-tools";
urlFix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
urlFix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
urlFix("Sample Text"); // "Sample Text"
```
### Bill calculator
| Method | Description | Return type |
| ------------------------- | --------------------------------------------------------------------------------------------------------- | ----------- |
| `getResult` | Result of bill calculated information | BillResult |
| `getAmount` | Calculate Bill amount by payment id and bill id which entered by the Bill constructor | number |
| `getBillType` | Get Bill provider type name | BillTypes |
| `getBarcode` | Calculate and get Bill's barcode | `string` |
| `verificationBill` | Validate entered both Bill id and payment id, and return true if bill id and payment id relation was true | boolean |
| `verificationBillId` | Validate entered Bill id | `boolean` |
| `verificationBillPayment` | Validate entered Bill payment id | `boolean` |
```js
import { Bill } from "@persian-tools/persian-tools";
// Calculate bill amount by bill id and payment id
// Convert to Iranian Rials
// Return bill amount by Toman(Iranian currency type) by default
new Bill({ billId: 1117753200140, paymentId: 12070160, currency: "rial" }).getResult().amount; // 120000
// Find Bill's type by bill id and payment id
new Bill({ billId: 7748317800142, paymentId: 1770160 }).getResult().type; // تلفن ثابت
new Bill({ billId: 9174639504124, paymentId: 12908197 }).getResult().type; // برق
new Bill({ billId: 2050327604613, paymentId: 1070189 }).getResult().type; // آب
new Bill({ billId: 9100074409151, paymentId: 12908190 }).getResult().type; // تلفن همراه
new Bill({ billId: 7748317800105, paymentId: 1770160 }).getResult().type; // unknown
// Check Bill id validation
new Bill({ billId: 7748317800142, paymentId: 1770160 }).getResult().isValidBillId; // true
new Bill({ billId: 2234322344613, paymentId: 1070189 }).getResult().isValidBillId; // false
// Check Bill's payment id validation
new Bill({ billId: 7748317800142, paymentId: 1770160 }).getResult().isValidBillPayment; // true
new Bill({ billId: 9174639504124, paymentId: 12908197 }).getResult().isValidBillPayment; // false
// Check Bill id and payment id relations which is valid or not
new Bill({ billId: 7748317800142, paymentId: 1770160 }).getResult().isValid; // true
new Bill({ billId: 2234322344613, paymentId: 1070189 }).getResult().isValid; // false
// Get barcode from billId and paymentId
new Bill({ billId: 7748317800142, paymentId: 1770160 }).getResult().barcode; // 77483178001420001770160
new Bill({ billId: 9174639504124, paymentId: 12908197 }).getResult().barcode; // 917463950412400012908197
// Get bill bill id and payment id by bill's barcode
new Bill({ barcode: "22343223446130001070189" }).findByBarcode(); // { billId: 2234322344613 , paymentId: 1070189 }
```
### Iranian Sheba(IBAN)
- Check validation
```javascript
import { isShebaValid } from "@persian-tools/persian-tools";
isShebaValid("IR820540102680020817909002"); // true
isShebaValid("IR01234567890123456789"); // false
```
- Recognize bank information
```javascript
import { getShebaInfo } from "@persian-tools/persian-tools";
getShebaInfo("IR820540102680020817909002");
/*
Result: {
"nickname": "parsian",
"name": "Parsian Bank",
"persianName": "بانک پارسیان",
"code": "054",
"accountNumberAvailable": true,
"accountNumber": "020817909002",
"formattedAccountNumber": "002-00817909-002"
}
*/
```
### Fix Persian zero-width non-joiner(Replace spaces by half-space)
```javascript
import { halfSpace } from "@persian-tools/persian-tools";
halfSpace("نمی خواهی درخت ها را ببینیم؟"); // "نمیخواهی درختها را ببینیم؟"
```
### Get information(province, category, type) about vehicles plate
| Properties | Description | Return type |
| ---------- | ------------------------------- | -------------- |
| `info` | provide info about plate | PlateResultApi |
| `isValid` | checks if plate is valid or not | boolean |
**Usage**
```js
import { getNumberPlateInfo } from "@persian-tools/persian-tools";
getNumberPlateInfo("12D45147"); // passing string argument
// or passing in object style
getNumberPlateInfo({
number: "1245147",
char: "الف",
});
```
- Getting info about plate
```js
import { getNumberPlateInfo } from "@persian-tools/persian-tools";
getNumberPlateInfo("12D45147").info;
/*
{
template: 12 D 451 ایران 47
province: مرکزی ,
type: Car,
category: دیپلمات,
details: {
firstTwoDigits: 12,
plateCharacter: D,
nextThreeDigits: 451,
provinceCode: 47
}
}
*/
// handle motorcyles plate
getNumberPlateInfo(12345678).info;
/*
{
template: 123-45678,
province: مرکز تهران,
type: Motorcyle,
category: null,
details: {
digits: 45678
provinceCode:123
}
}
*/
```
Plates that have farsi digits in them(like: الف، ب، ص) will be returned in this template
```
${first_two_digits}${plate_character}${next_three_digits}ایران${province_code}
```
- Checking if plate is valid
```js
import { getNumberPlateInfo } from "@persian-tools/persian-tools";
getNumberPlateInfo("12D45147").isValid;
/*
true
*/
getNumberPlateInfo(12345678).isValid;
/*
true
*/
getNumberPlateInfo(1234567).isValid;
/*
will return false - plate character is not provided
*/
getNumberPlateInfo(1204567).isValid;
/*
will return false - plate can't have 0 in its digits (except last digit)
*/
```
### Convert Jalaali date-time into a time ago
**Usage**
> Suppose the current time is equal to `1400/03/17 18:00:00`
```js
import { timeAgo } from "@persian-tools/persian-tools";
// Previous
timeAgo("1400/03/17 17:55:00"); // 5 دقیقه قبل
timeAgo("1400/02/17 18:00:00"); // حدود 1 ماه قبل
// Next
timeAgo("1400/04/07 18:00:00"); // حدود 3 هفته بعد
timeAgo("1401/03/17 18:00:00"); // حدود 1 سال بعد
```
### Get the Remaining Time of the Date
**Usage**
> Takes a date(it could be string, number or date) and calculate years,
> months, days, hours, minutes and seconds remained to that specific date.
```js
import { remainingTime } from "@persian-tools/persian-tools";
remainingTime("2023-05-14T13:35:59Z").toString(); // ۱ سال و ۱ ماه و ۲ روز و ۳ ساعت و ۵ دقیقه و ۸ ثانیه
const { years, months, days, hours, minutes, seconds, isFinished } = remainingTime("2023-05-14T13:35:59Z");
years; // 1
minutes; // 5
isFinished; // false
remainingTime("2018-04-12T10:30:51Z").isFinished; // true
```
### Validate and find information of phone number
**Usage**
- Finding information such as province, type and model of phone number
```js
import { phoneNumberDetail } from "@persian-tools/persian-tools";
phoneNumberDetail("9123456789");
/*
{
province: ["البرز", "زنجان", "سمنان", "قزوین", "قم", "برخی از شهرستان های استان مرکزی"],
base: "تهران",
operator: "همراه اول",
type: ["permanent"],
}
*/
phoneNumberDetail("09301234567");
/*
{
province: [],
base: "کشوری",
operator: "ایرانسل",
type: ["permanent", "credit"],
}
*/
phoneNumberDetail("09981000000");
/*
{
province: [],
base: "کشوری",
operator: "شاتل موبایل",
type: ["credit"],
}
*/
```
- Validating phone number
```js
import { isPhoneNumberValid } from "@persian-tools/persian-tools";
isPhoneNumberValid("09122002580"); // true
isPhoneNumberValid("09192002580"); // true
isPhoneNumberValid("+989122002580"); // true
isPhoneNumberValid("09122002580"); // true
isPhoneNumberValid("989122002580"); // true
isPhoneNumberValid("00989122002580"); // true
isPhoneNumberValid("9122002580"); // true
isPhoneNumberValid("09812002580"); // false
```
- Normalizing phone number
```js
import { phoneNumberNormalizer } from "@persian-tools/persian-tools";
phoneNumberNormalizer("+989122002580", "0"); // 09122002580
phoneNumberNormalizer("989122002580", "0"); // 09122002580
phoneNumberNormalizer("09122002580", "0"); // 09122002580
phoneNumberNormalizer("09122002580", "+98"); // +989122002580
```
### Find capital city by province name
**Usage**
> This function returns the Capital City name by its state name. if it can't find anything, it will throws an error.
```js
import { findCapitalByProvince } from "@persian-tools/persian-tools";
findCapitalByProvince("خراسان رضوی"); // مشهد
findCapitalByProvince("آذربایجان شرقی"); // تبریز
// this throw an error string 'no province found'
findCapitalByProvince("دبی");
```
### Find province from coordinate
**Usage**
> Find the province from a given coordinate point. If it cannot find anything, it will throw an error.
```javascript
import { findProvinceFromCoordinate } from "@persian-tools/persian-tools";
// Find province for a given coordinate point
const point = { latitude: 35.6892, longitude: 51.389 };
const province = findProvinceFromCoordinate(point);
province.fa; // "تهران"
province.en; // "Tehran"
// shorthand syntax using destructuring
const { fa, en } = findProvinceFromCoordinate(point);
```
### Todo
- [ ] Write Jalaali and Gregorian functions to convert Date together.
## Contributing
Thank you for your interest in contributing! Please feel free to put up a PR for any issue or feature request.
## License
This project is licensed under the MIT License - see the [LICENSE.md](https://github.com/ali-master/persian-tools/blob/master/LICENSE) file for details.
## Who's using Persian tools?

Pooleno Exchange

Bank Maskan

MyDong

Melkba
If you're curious to see what can be accomplished with Persian tools, check out these apps!
If you have a software you'd like to see added, please
[open a pull request](https://help.github.com/articles/creating-a-pull-request/)!
All that's required is a name, link, and a PNG icon.
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):

Ali Torki
🚇 ⚠️ 💻

mssoheil
⚠️ 💻

Mohsen
⚠️ 💻

Hesam pourghazian
💻

Amir Hossien Qasemi Moqaddam
💻

SeyyedKhandon
💻

msdDaliriyan
💻 ⚠️

Mahdi
💻 ⚠️ 📖

PS-PARSA
⚠️ 💻 🤔

Amirhossein Douzandeh Zenoozi
💻 ⚠️ 🤔

M0rteza-M
💻 ⚠️

mediv0
💻 ⚠️ 🤔

Poorshad Shaddel
💻 ⚠️ 🤔

Seyed Masih Sajadi
💻 ⚠️

Mohammad Ghonchesefidi
💻 ⚠️

Saeed Hasani Borzadaran
💻 ⚠️

Ali Madihi
💻

Amir
📖

Kaveh Karami
💻

Mehdi Shah abbasian
📖
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
# Supporters :open_hands:
[](https://github.com/persian-tools/persian-tools/stargazers)