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

后端 未结 9 997
萌比男神i
萌比男神i 2020-12-05 04:15

How can I convert Persian/Arabic numbers to English numbers with a simple function?

arabicNumbers = [\"١\", \"٢\", \"٣\", \"٤\", \"٥\", \"٦\", \"٧\", \"٨\",          


        
9条回答
  •  眼角桃花
    2020-12-05 04:28

    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

提交回复
热议问题