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

后端 未结 9 1008
萌比男神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:51

    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]
    

提交回复
热议问题