-2

I have an input field with type number, my issue is when using Firefox and safari with Arabic keyboard the number are written ٨٦٥ like that, how can I convert this format to 8754 (English format) while the user typing in the filed? Or i prevent it from typing non English format.

Noarah
  • 19
  • 8
  • Your question matches this => https://stackoverflow.com/questions/31439604/how-to-convert-persian-and-arabic-digits-of-a-string-to-english-using-javascript –  Nov 25 '21 at 16:26
  • This convert the number after it displayed, I need to convert it while user typing in the field (act like it's in chrome) – Noarah Nov 25 '21 at 23:32
  • possible solution added below. – Mohsen Alyafei Jan 09 '22 at 08:51

2 Answers2

1

The following function will change the field key pressed value of the numbers 0123456789 to the Arabic-Eastern form "٠١٢٣٤٥٦٧٨٩".

if you type 1 it will show ١,

if you type 2 it will show ٢, and so on.

It will not affect the other characters.

It can be improved.

document.getElementById('myTextFieldId').addEventListener("keypress", function(e){
let code=e.keyCode-48;
        if (code>=0 && code<10) {
        e.target.value = e.target.value.slice(0,e.target.selectionStart)
        + "٠١٢٣٤٥٦٧٨٩"[code]
        + e.target.value.slice(e.target.selectionEnd);
        e.target.selectionStart = e.target.selectionEnd = e.target.selectionStart + 1;
        e.preventDefault();
            }
        })
<input type="text" id="myTextFieldId" />
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42
-1

you can try this:

function arabicToLatinNumbers(arabicNumber){
  let result = "";

  const arabic1 = '١'.charCodeAt(0);
  const english1 = '1'.charCodeAt(0);

  for(i = 0; i < arabicNumber.length; i++){
     result += String.fromCharCode(arabicNumber.charCodeAt(i) - arabic1 + 
     english1);
  }
  return result;
}

const result = arabicToLatinNumbers('٣٤');
console.log(result);//prints 34
DSMSTHN
  • 40
  • 4