Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
تبدیل عدد از انگلیسی به فارسی / عربی در جاوا اسکریپت - 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

senior-x-79 commented Jan 20, 2022

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

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