Search code examples
javascriptjqueryhtml

Convert input language while typing in


I have an input field that accepts two languages Arabic and English, what i want is when i type Arabic numbers into this input to convert them into English while the user is typing, i want them to be converted from ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'] to ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], how can i do that? here is my input code:

<input type="text" placeholder="Numbers should be converted from Arabic to English here">


Solution

  • Use the oninput handler on the input to watch for updates in the text field. Then use a String#replace on the input element's value to replace all digits with the one you need.

    The replace method can take a function and I used that function In the code below to map the digit directly to the arabic representation by its index in the map array.

    let map =  ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    
    function change(el){
      el.value = el.value.replace(/\d/g, function(match){
        return map[match]
      })
    }
    <input type="text" placeholder="Numbers should be converted from Arabic to English here" oninput="change(this)">

    **EDIT**

    I'm tripping. OP wanted to go from Arabic to English. Just change map into an object mapping the arabic representation to the english and then change the regular expression inside replace to capture the arabic instead of digits.

    let map =  {
      '۰' : "0", 
      '۱' : "1", 
      '۲' : "2", 
      '۳' : "3", 
      '۴' : "4",
      '۵' : "5", 
      '۶' : "6", 
      '۷' : "7",
      '۸' : "8", 
      '۹' : "9"
     };
    
    function change(el){
      el.value = el.value.replace(/[۰۱۲۳۴۵۶۷۸۹]/g, function(match){
        return map[match]
      })
    }
    <input type="text" placeholder="Numbers should be converted from Arabic to English here" oninput="change(this)">