HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptModerate

Convert Persian digits to English numbers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
englishconvertdigitsnumberspersian

Problem

I use the following code to convert ۱۲۳۴۵ to ‍12345, effectively transliterating the persian numbers into latin numbers:

String.prototype.toEnglishDigits = function () {
var num_dic = {
'۰': '0',
'۱': '1',
'۲': '2',
'۳': '3',
'۴': '4',
'۵': '5',
'۶': '6',
'۷': '7',
'۸': '8',
'۹': '9',
}

return parseInt(this.replace(/[۰-۹]/g, function (w) {
return num_dic[w]
}));
}

console.log('۱۲۳۴۵'.toEnglishDigits());

Solution

Instead of using a map,
you can get the corresponding digits directly by subtracting the character code of '۰'.
That is, since the character code of '۳' is 1779
and the character code of '۰' is 1776, you can calculate that:

'۳'.charCodeAt(0) - '۰'.charCodeAt(0) = 1779 - 1776 = 3


Using the above logic, the function can be written shorter:

String.prototype.toEnglishDigits = function () {
    var charCodeZero = '۰'.charCodeAt(0);
    return parseInt(this.replace(/[۰-۹]/g, function (w) {
        return w.charCodeAt(0) - charCodeZero;
    }));
}

Code Snippets

'۳'.charCodeAt(0) - '۰'.charCodeAt(0) = 1779 - 1776 = 3
String.prototype.toEnglishDigits = function () {
    var charCodeZero = '۰'.charCodeAt(0);
    return parseInt(this.replace(/[۰-۹]/g, function (w) {
        return w.charCodeAt(0) - charCodeZero;
    }));
}

Context

StackExchange Code Review Q#97162, answer score: 13

Revisions (0)

No revisions yet.