javascriptjquerynumbersnumber-formattingfarsi

Convert English numbers to Persian/Farsi or Arabic only for a specified div


I know this question has been asked many times here, but I still haven't got an exact answer. I need to convert English digits to Persian (Farsi) or Arabic digits by some JavaScript, but not for the entire page, but only for a div or more. Like only for a specific class.

I have come across these codes, but don't know which one are the best to use.

function convert($string) {
    $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    $num = range(0, 9);
    return str_replace($persian, $num, $string);
}

I need exactly that source to implement only on one div-class. For example:

<div class="demo">12345</div> 

should change to

<div class="demo">۱۲۳۴۵</div>

Solution

  • I don't believe either of the code samples you provided are JavaScript, the first is close syntactically, but is missing the range() method and new on the array() definition. The second is Java.

    To achieve what you require you could convert the text of each of the HTML elements you want to translate to an array and step through them, checking each character via Regex to see if a number was found. If it was, you can do a simple replacement before joining the array back together. Something like this:

    var arabicNumbers = ['۰', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
    $('.translate').text(function(i, v) {
      var chars = v.split('');
      for (var i = 0; i < chars.length; i++) {
        if (/\d/.test(chars[i])) {
          chars[i] = arabicNumbers[chars[i]];
        }
      }
      return chars.join('');
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="translate">Dummy text with some 123 numbers in 390981 it.</div>
    <div class="translate">Dummy text with some 67898 numbers in 109209734.09 it.</div>


    Update - 2020-03

    Here's a shorter version of the above logic using ES6 syntax. Note that this will work in all modern browsers. The only place it won't work is in any version of IE.

    var arabicNumbers = ['۰', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
    $('.translate').text((i, v) => v.split('').map(c => parseInt(c) ? arabicNumbers[parseInt(c)] : c).join(''));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="translate">Dummy text with some 123 numbers in 390981 it.</div>
    <div class="translate">Dummy text with some 67898 numbers in 109209734.09 it.</div>