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

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

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

提交回复
热议问题