'How to detect user keyboard is Persian or English when press numeric keys

I want to detect that the user keyboard is English or Persian when it press numeric keys.

I'm using following code for non numeric keys, but it doesn't work on numeric keys!

  <input type="text" onkeyup="findType(this)">
<script>
  function findType(element) {
    let char = new RegExp("[\u0600-\u06FF]");
    if (char.test(element.value) === true) {
        element.style.direction =  "rtl"
    }
    else {
        element.style.direction =  "ltr"
    }
}
</script>

Persian digits 0 to 9 unicode are from &#1776 to &#1785



Solution 1:[1]

one way to approach this problem is to take advantage of navigator.language Here is a reference to the documentation

let keyboard = () => {
  let lang = navigator.language;
  if (lang === 'ar') {
    return 'arabic';
  }
}
window.onload = keyboard;

This worked when I switched my Chrome Browser default language to Arabic, and I was able to detect the language switch. A quick note, it did not work when I enabled the keyboard on my MAC to Arabic.

Once we have detected the keyboard language you can complete the remainder of your tasks.

For older Internet Explorer browsers, I believe you need to use window.navigator.userLanguage depending on the level of support your task requirements.

Another idea, might be to test to data type of the key being pressed, assuming the data types might be different from country to country

let key_pressed = (e) => {
  let key = e.keyCode;
  return typeof key;
}

window.addEventListener('keydown', (e) => {
  let key = key_pressed(e);
  console.log(key);
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1