Search code examples
javascriptnumbersnanarabictranslate

Convert only Arabic numbers to English in a text input


I have found this function which works perfectly when text input is only Arabic numbers:

function parseArabic(){ // PERSIAN (فارسی), ARABIC (عربي) , URDU (اُردُو)
     var yas ="٠١٢٣٤٥٦٧٨٩";
     yas = Number(yas.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function (d) {
         return d.charCodeAt(0) - 1632;                
         }).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function (d) { return d.charCodeAt(0) - 1776; })
     );
     alert(yas);
}

Here the alerted value of yas is "0123456789".Ok great but now how can I use this function when I have other characters in the same variable that could be english(letters and numbers) and arabic (letters)? Ex: "test ٠١٢٣٤٥٦٧٨٩ hello مرحبا " . I am asking this because parseArabic accepts only arabic numbers to be translated; others are considered as NaN.


Solution

  • For some one who does not want to take the pains of finding Number (as per OP's answer). Here is the updated code :

    function parseArabic(){ // PERSIAN (فارسی), ARABIC (عربي) , URDU (اُردُو)
         var yas ="٠١٢٣٤٥٦٧٨٩";
         yas = (yas.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function (d) {
             return d.charCodeAt(0) - 1632;                
             }).replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function (d) { return d.charCodeAt(0) - 1776; })
         );
         alert(yas);
    }