Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from English Digits to Arabic ones in html page

Tags:

I need to convert all English numbers that appear in a given HTML page to Arabic ones (to be independent from the user browser encoding). I prefer to use javascript or it will be great if this can be handled using CSS.

I found some pages doing this but I found that the Arabic letters are added with their ASCII representation in the source code. Does it mean that they are applying some sort of a java script function?

Any clue how can I do something like this?

like image 321
Sarah Avatar asked Nov 04 '09 18:11

Sarah


2 Answers

How about a straight replace function?

String.prototype.toIndiaDigits= function(){
 var id= ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
 return this.replace(/[0-9]/g, function(w){
  return id[+w]
 });
}

// test

var S='The year 2009 has only 365 days';
alert(S.toIndiaDigits());

/*  returned value: (String)
The year ۲۰۰۹ has only ۳۶۵ days
*/
like image 92
kennebec Avatar answered Nov 11 '22 19:11

kennebec


You will need to use JavaScript, but the procedure is quite straightforward. Assuming that the number you wish to convert is already in a string, then something like the following snippet of code will work:

function convertDigitIn(enDigit){ // PERSIAN, ARABIC, URDO
    var newValue="";
    for (var i=0;i<enDigit.length;i++)
    {
        var ch=enDigit.charCodeAt(i);
        if (ch>=48 && ch<=57)
        {
            // european digit range
            var newChar=ch+1584;
            newValue=newValue+String.fromCharCode(newChar);
        }
        else
            newValue=newValue+String.fromCharCode(ch);
    }
    return newValue;
}

The code isn't very pretty and can probably be written more efficiently, but essentially what it's doing is converting any char from "0" to "9" by adding an offset value to make the character value now be in the unicode range for the Indic digits. The Indic digits range from \u0660 to \u0669 hence the conversion from European to Indic digits is just simple maths.

like image 38
ferdley Avatar answered Nov 11 '22 19:11

ferdley