javascriptnumbersarabictranslatefarsi

Convert only Persian/Farsi or Arabic numbers to English in a text input


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

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

Here, the new 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)? For example, "test ٠١٢٣٤٥٦٧٨٩ hello مرحبا ". I am asking this because parsePersianOrArabic() accepts only Persian and 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 parsePersianOrArabic() { // PERSIAN (فارسی), ARABIC (عربي) , URDU (اُردُو)
        var yas = "٠١٢٣٤٥٦٧٨٩";
        yas = yas
            // Arabic digits
            .replace(/[٠١٢٣٤٥٦٧٨٩]/g, function (d) {
                return d.charCodeAt(0) - 1632/*==unicode value of arabic digit zero ٠*/;
            })
            // Persian/Farsi/Urdu digits
            .replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function (d) {
                return d.charCodeAt(0) - 1776/*==unicode value of Persian digit zero ۰*/;
            });
        alert(yas);
    }