0

I'm trying to either custom a pipe to convert numbers to Arabic or Persians, or find a function to convert numbers to Arabic numbers.

I've one function but it doesn't to give me a stable result,

for example I've this date : 1400/2/2 ---> ۲/۲/۱٤۰۰

     arabicNumbers = ['۰', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];

  convertToArabic = (number) => {
    return String(number).split('').map(char => {
      if (char === '/') {
        return '/';
      } else {
        return this.arabicNumbers[Number(char)]
      }
    }
    ).join('');
  }

this function doesn't give a stable result, it keeps switching the numbers' order.

I hope you can help me solve this

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
ayay
  • 31
  • 5
  • 1
    Can you provide a [mcve] which actually demonstrates how the order "keeps switching"? I mean, I can imagine that maybe you're running into RTL and LTR issues, since Arabic is a Right-to-Left language and English is not, as in [this question](https://stackoverflow.com/questions/4989346/how-mixing-ltr-and-rtl-languages-is-managed-in-unicode), but I can't tell if this is a duplicate or not because I haven't seen the issue you're mentioning firsthand. – jcalz Feb 18 '21 at 21:59
  • 1
    You're code seems to work as I expect it to: https://jsfiddle.net/qfrs415g/ I suspect jcalz is right about this being an issue with RTL text directions which has nothing to do with your posted code. – Alex Wayne Feb 18 '21 at 22:02
  • I've like 2000 row in my database but when I display them some of them only some changes orders. – ayay Feb 18 '21 at 22:31
  • how do I make sure the order direction stay the same – ayay Feb 18 '21 at 22:31
  • how to custom a pipe that convert the numbers – ayay Feb 18 '21 at 22:34

1 Answers1

0

You can convert Arabic or Persian numbers to Latin (English) and keep the remaining text unchanged with the following 2 simple one-liner examples:

const numLatinToAr=n=>n.replace(/\d/g,d=>"٠١٢٣٤٥٦٧٨٩"[d]);
const numLatinToFa=n=>n.replace(/\d/g,d=>"۰۱۲۳۴۵۶۷۸۹"[d]);


console.log(numLatinToAr("1400/2/2"));  // to Arabic
console.log(numLatinToFa("1400/2/2"));  // to Persian
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42