Skip to content

Instantly share code, notes, and snippets.

@senior-x-79
Created January 20, 2022 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save senior-x-79/64671080bd85dde13317348f2baf429e to your computer and use it in GitHub Desktop.
Save senior-x-79/64671080bd85dde13317348f2baf429e to your computer and use it in GitHub Desktop.
تبدیل عدد از انگلیسی به فارسی / عربی در جاوا اسکریپت - how to convert english number to Persian/Arabic Number
// METHOD 1
const numFa = new Intl.NumberFormat('fa-IR', {style : "decimal" }).format(987654321).replace(/٬/g , "")
const numAr = new Intl.NumberFormat('ar-AE', {style : "decimal" }).format(987654321).replace(/٬/g , "")
console.log(numFa); // ۹۸۷۶۵۴۳۲۱
console.log(numAr); // ٩٨٧٦٥٤٣٢١
// METHOD 2
String.prototype.getBaseConversionNumber = function(label){
const faDigits = ['۱','۲','۳','۴','۵','۶','۷','۸','۹','۰'];
const enDigits = ['1','2','3','4','5','6','7','8','9','0'];
const arDigits = ['٠','٩','٨','٧','٦','٥','٤','٣','٢','١']
var whichDigit = {};
switch(label){
case 'fa':
whichDigit[label] = faDigits;
break;
case 'en':
whichDigit[label] = enDigits;
break;
case 'ar':
whichDigit[label] = arDigits;
break;
case 'all':
whichDigit = {"fa" : faDigits, "en" : enDigits, "ar" : arDigits};
break;
default:
whichDigit = [];
}
return whichDigit;
}
String.prototype.CvnFromTo = function(fromDigits,toDigits,str){
var str = str == undefined ? this : str;
for(var i=0;i<toDigits.length;i++){
const currentFromDigit = fromDigits[i];
const currentToDigit = toDigits[i];
const regex = new RegExp(currentFromDigit,'g');
str = str.replace(regex, currentToDigit);
}
return str;
}
String.prototype.convertDigits = function(to){
let str = this;
const toCvn = (this.getBaseConversionNumber(to))[to];
const allDigits = this.getBaseConversionNumber("all");
delete allDigits[to];
const Objkeys = Object.keys(allDigits);
for(var i=0;i<Objkeys.length;i++){
const currentKey = Objkeys[i];
const fromCvn = allDigits[currentKey];
str = this.CvnFromTo(fromCvn,toCvn,str)
}
return str;
}
const myNumber = 987654321;
const intFa = myNumber.toString().convertDigits("fa");
const intAr = myNumber.toString().convertDigits("ar");
const intUs = intFa.convertDigits("en");
console.log(intFa); // ۹۸۷۶۵۴۳۲۱
console.log(intAr); // ٩٨٧٦٥٤٣٢١
console.log(intUs); // 987654321
@senior-x-79
Copy link
Author

کد باحال 😎 بالا برای این مقاله می باشد

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment