How to convert Persian and Arabic numbers inside a string to English using JavaScript?

荒凉一梦 提交于 2019-11-30 18:18:01

Use this simple function to convert your string

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.

Example

var mystr = 'Sample text ۱۱۱۵۱ and ٢٨٢٢';
mystr = fixNumbers(mystr);

Refrence

Transforms any Persian or Arabic (or mixed) number to "English" numbers (Hindu–Arabic numerals)

var transformNumbers = (function(){
    var numerals = {
        persian : ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
        arabic  : ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
    };

    function fromEnglish(str, lang){
        var i, len = str.length, result = "";

        for( i = 0; i < len; i++ )
            result += numerals[lang][str[i]]; 

        return result;
    }

    return {
        toNormal : function(str){
            var num, i, len = str.length, result = "";

            for( i = 0; i < len; i++ ){
                num = numerals["persian"].indexOf(str[i]);
                num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
                if( num == -1 ) num = str[i];
                result += num; 
            }
              
            return result;
        },

        toPersian : function(str, lang){
            return fromEnglish(str, "persian");
        },

        toArabic : function(str){
            return fromEnglish(str, "arabic");
        }
    }
})();

//////// ON INPUT EVENT //////////////

document.querySelectorAll('input')[0].addEventListener('input', onInput_Normal);
document.querySelectorAll('input')[1].addEventListener('input', onInput_Arabic);

function onInput_Arabic(){
   var _n = transformNumbers.toArabic(this.value);
   console.clear();
   console.log( _n )
}

function onInput_Normal(){
   var _n = transformNumbers.toNormal(this.value);
   console.clear();
   console.log( _n )
}
input{ width:90%; margin-bottom:1em; font-size:1.5em; padding:5px; }
<input placeholder="write in Arabic numerals">

<input placeholder="write in normal numerals">
alireza ahmadi beni

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);
    });
};

this is a simple way to do that:

function toEnglishDigits(str) {

    // convert persian digits [۰۱۲۳۴۵۶۷۸۹]
    var e = '۰'.charCodeAt(0);
    str = str.replace(/[۰-۹]/g, function(t) {
        return t.charCodeAt(0) - e;
    });

    // convert arabic indic digits [٠١٢٣٤٥٦٧٨٩]
    e = '٠'.charCodeAt(0);
    str = str.replace(/[٠-٩]/g, function(t) {
        return t.charCodeAt(0) - e;
    });
    return str;
}

an example:

console.log(toEnglishDigits("abc[0123456789][٠١٢٣٤٥٦٧٨٩][۰۱۲۳۴۵۶۷۸۹]"));
// expected result => abc[0123456789][0123456789][0123456789]

Short and easy!

"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, function(token) { return String.fromCharCode(token.charCodeAt(0) - 1728); });
Ed Ballot

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));

Here is how I'd do it:

(strr => strr.replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]))("asdf1234")

asdf۱۲۳۴

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!