Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@persian-tools/persian-tools

Package Overview
Dependencies
Maintainers
1
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@persian-tools/persian-tools

An anthology of a variety of tools for Persian language in javascript

  • 3.5.2
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.7K
increased by22.61%
Maintainers
1
Weekly downloads
 
Created
Source

Persian tools

PersianTools is a standalone, library-agnostic JavaScript that enables some of the Persian features for use in the JavaScript.

Rate on Openbase CI/CD codecov GitHub license PRs Welcome CodeFactor GitHub contributors Wallaby.js


Features

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>
	<head>
		<!-- Load PersianTools.js -->
		<script src="https://cdn.jsdelivr.net/npm/@persian-tools/persian-tools/build/persian-tools.umd.js"></script>

		<!-- Place your code in the script tag below. You can also use an external .js file -->
		<script type="text/javascript">
			// 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...
		</script>
	</head>

	<body></body>
</html>

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.

$ npm install --save @persian-tools/persian-tools

or

$ yarn add @persian-tools/persian-tools

Simple usage

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

OptionsDescriptionDefault
fuzzy(Beta)Fix typo in the Persian words by using levenshtein algorithmfalse
digitsResult will be converted to the English or Persian digitsen
addCommasCommas will be added to the Resultfalse
  • Convert with no option
import { wordsToNumber } from "@persian-tools/persian-tools";

wordsToNumber("منفی سه هزارمین"); // -3000
wordsToNumber("منفی سه هزارم"); // -3000
wordsToNumber("منفی سه هزار"); // -3000
wordsToNumber("سه هزار دویست و دوازده"); // 3212
wordsToNumber("دوازده هزار بیست دو"); // 12022
  • Digits converter
wordsToNumber("منفی سه هزارمین", { digits: "fa" }); // "-۳۰۰۰"
wordsToNumber("دوازده هزار بیست دو", { digits: "fa" }); // ۱۲۰۲۲
  • Add commas
wordsToNumber("منفی سه هزارمین", { addCommas: true }); // "-3,000"
wordsToNumber("دوازده هزار بیست دو", { addCommas: true }); // "12,022"
  • Fuzzy typo fixer(v1.5.0):
import { WordsToNumber } from "@persian-tools/persian-tools";

wordsToNumber("یگصد و بنجاه هزار", { fuzzy: true }); // "150000"
wordsToNumber("دویشت ر بیشت هزار", { fuzzy: true }); // "220000"
wordsToNumber("منقی ضد", { fuzzy: true }); // "-100"

Convert Numbers to Persian words

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

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

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)

import { verifyIranianNationalId, getPlaceByIranNationalId } from "@persian-tools/persian-tools";

verifyIranianNationalId("0499370899"); // true
verifyIranianNationalId("0684159415"); // false
import { verifyIranianLegalId } from "@persian-tools/persian-tools";

verifyIranianLegalId(10380285692); // false
verifyIranianLegalId(10380284790); // true

Find city and province name by national-id(code-e Melli)

getPlaceByIranNationalId("0084575948").city; // "تهران مرکزی"

Bank number validation and get the name of the bank by bank account number

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.

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.

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

MethodDescriptionReturn type
getResultResult of bill calculated informationBillResult
getAmountCalculate Bill amount by payment id and bill id which entered by the Bill constructornumber
getBillTypeGet Bill provider type nameBillTypes
getBarcodeCalculate and get Bill's barcodestring
verificationBillValidate entered both Bill id and payment id, and return true if bill id and payment id relation was trueboolean
verificationBillIdValidate entered Bill idboolean
verificationBillPaymentValidate entered Bill payment idboolean
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
import { isShebaValid } from "@persian-tools/persian-tools";

isShebaValid("IR820540102680020817909002"); // true
isShebaValid("IR01234567890123456789"); // false
  • Recognize bank information
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)

import { halfSpace } from "@persian-tools/persian-tools";

halfSpace("نمی ‌خواهی درخت ها را ببینیم؟"); // "نمی‌خواهی درخت‌ها را ببینیم؟"

Get information(province, category, type) about vehicles plate

PropertiesDescriptionReturn type
infoprovide info about platePlateResultApi
isValidchecks if plate is valid or notboolean

Usage

import { Plate } from "@persian-tools/persian-tools";

Plate("12D45147"); // passing string argument

// or passing in object style
Plate({
	number: "1245147",
	char: "الف",
});
  • Getting info about plate
import { Plate } from "@persian-tools/persian-tools";

Plate("12D45147").info;
/*
  {
  	template: 12 D 451 ایران  47
    province: مرکزی ,
    type: Car,
	category: دیپلمات,   
    details: {
	firstTwoDigits: 12,
	plateCharacter: D,
	nextThreeDigits: 451,
	provinceCode: 47
    }
  }
*/

// handle motorcyles plate
Plate(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
import { Plate } from "@persian-tools/persian-tools";

Plate("12D45147").isValid;
/*
  true
*/

Plate(12345678).isValid;
/*
  true
*/

Plate(1234567).isValid;
/*
  will return false - plate character is not provided
*/

Plate(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

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.

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
import { phoneNumberDetail } from "@persian-tools/persian-tools";

phoneNumberDetail("9123456789");
/*
  {
    province: ["البرز", "زنجان", "سمنان", "قزوین", "قم", "برخی از شهرستان های استان مرکزی"],
    base: "تهران",
    operator: "همراه اول",
    type: ["permanent"],
  }
*/

phoneNumberDetail("09022002580");
/*
  {
    province: [],
    base: "کشوری",
    operator: "ایرانسل",
    type: ["permanent", "credit"],
  }
*/

phoneNumberDetail("09981000000");
/*
  {
    province: [],
    base: "کشوری",
    operator: "شاتل موبایل",
    type: ["credit"],
  }
*/
  • Validating phone number
import { phoneNumberValidator } from "@persian-tools/persian-tools";

phoneNumberValidator("09122002580"); // true
phoneNumberValidator("09192002580"); // true

phoneNumberValidator("+989022002580"); // true
phoneNumberValidator("09022002580"); // true
phoneNumberValidator("989022002580"); // true
phoneNumberValidator("00989022002580"); // true
phoneNumberValidator("9022002580"); // true

phoneNumberValidator("09802002580"); // false
  • Normalizing phone number
import { phoneNumberNormalizer } from "@persian-tools/persian-tools";

phoneNumberNormalizer("+989022002580", "0"); // 09022002580
phoneNumberNormalizer("989022002580", "0"); // 09022002580
phoneNumberNormalizer("09022002580", "0"); // 09022002580
phoneNumberNormalizer("09022002580", "+98"); // +989022002580

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.

import { findCapitalByProvince } from "@persian-tools/persian-tools";

findCapitalByProvince("خراسان رضوی"); // مشهد
findCapitalByProvince("آذربایجان شرقی"); // تبریز

// this throw an error string 'no province found'
findCapitalByProvince("دبی");

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 file for details.

Who's using Persian tools?


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! All that's required is a name, link, and a PNG icon.

Contributors ✨

Thanks goes to these wonderful people (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 specification. Contributions of any kind welcome!

Supporters :open_hands:

Stargazers repo roster for @persian-tools/persian-tools

Keywords

FAQs

Package last updated on 09 Jan 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc