How can I convert Persian/Arabic numbers to English numbers with a simple function?
arabicNumbers = [\"١\", \"٢\", \"٣\", \"٤\", \"٥\", \"٦\", \"٧\", \"٨\",
var
persianNumbers = [/۰/g, /۱/g, /۲/g, /۳/g, /۴/g, /۵/g, /۶/g, /۷/g, /۸/g, /۹/g],
arabicNumbers = [/٠/g, /١/g, /٢/g, /٣/g, /٤/g, /٥/g, /٦/g, /٧/g, /٨/g, /٩/g],
fixNumbers = function (str)
{
if(typeof str === 'string')
{
for(var i=0; i<10; i++)
{
str = str.replace(persianNumbers[i], i).replace(arabicNumbers[i], i);
}
}
return str;
};
Be careful, in this code the persian numbers codepage are different with the arabian numbers.
var mystr = 'Sample text ۱۱۱۵۱ and ٢٨٢٢';
mystr = fixNumbers(mystr);
Refrence
You could do something like this that uses the index of the number within the string to do the conversion:
// Returns -1 if `fromNum` is not a numeric character
function convertNumber(fromNum) {
var persianNums = '۰١۲۳۴۵۶۷۸۹';
return persianNums.indexOf(fromNum);
}
var testNum = '۴';
alert("number is: " + convertNumber(testNum));
Or map using a object like this:
// Returns -1 if `fromNum` is not a numeric character
function convertNumber(fromNum) {
var result;
var arabicMap = {
'٩': 9,
'٨': 8,
'٧': 7,
'٦': 6,
'٥': 5,
'٤': 4,
'٣': 3,
'٢': 2,
'١': 1,
'٠': 0
};
result = arabicMap[fromNum];
if (result === undefined) {
result = -1;
}
return result;
}
var testNum = '٤';
alert("number is: " + convertNumber(testNum));
best way to do that return index of number in array:
String.prototype.toEnglishDigits = function () {
return this.replace(/[۰-۹]/g, function (chr) {
var persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return persian.indexOf(chr);
});
};
Short and easy!
"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, function(token) { return String.fromCharCode(token.charCodeAt(0) - 1728); });
Or in a more modern manner
"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728));
function toEnglishDigits(str) {
const persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"]
const arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"]
const englishNumbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
return str.split("").map(c => englishNumbers[persianNumbers.indexOf(c)] ||
englishNumbers[arabicNumbers.indexOf(c)] || c).join("")
}
toEnglishDigits("۶٦۵any٥32") // "665any532"
If the string may contain both "Arabic" and "Persian" numbers then a one-line "replace" can do the jo as follows.
The Arabic and Persian numbers are converted to English equivalents. Other text remains unchanged.
Num= "۳٣۶٦۵any٥۵٤۶32٠۰"; // Output should be "33665any55453200"
Num = Num.replace(/[٠-٩]/g, d => "٠١٢٣٤٥٦٧٨٩".indexOf(d)).replace(/[۰-۹]/g, d => "۰۱۲۳۴۵۶۷۸۹".indexOf(d));
console.log(Num);