Polla A. Fattah
Polla A. Fattah

Reputation: 829

JavaScript: Convert Hindi numeral to Arabic one on fly while typing in an input text

I am trying to create a JavaScript code to convert Hindi Numerals [١،٢،٣،٤،٥،٦] to Arabic numeral [1,2,3,4,5,6] on fly. This means I am trying to convert numbers so that it is easier for programming languages. The problem what ever I do I can not get rid of the last pressed digit in Hindi so when I press ٢ I can change it to 2 but what happens I will get ٢2 at the same time. Would you please let me know how to implement that so that if the user inputs ١٠٠ in the textbox it will convert it to 100 on just like he is actually typeing 100 with the keyboard.

After too many attempts I have stopped here Which is not doing what I want

var digits = [1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1632];
var d = "";
function convert(event) {
    var x = event.which || event.charCode;
    var i = document.getElementById("barCode").value.length;

    if(digits.includes(x)){
        document.getElementById("barCode").value = String.fromCharCode(x - 1584);
    }

    console.log(i);
}
<p>A function is triggered when the user is pressing a key in the input field.</p>

<input type="text" id="barCode" keyup="convert(event)">

Upvotes: 1

Views: 555

Answers (1)

jeprubio
jeprubio

Reputation: 18012

You can use map but then the input should be an array and you can use split for this. At the end we return it to a string again with join:

var hindi = ['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];
var arabic = [0,1,2,3,4,5,6,7,8,9];

function translate(input) {
   var array = input.split('');
   array.map(function(value, i, array) {
     if (hindi.indexOf(array[i]) >= 0) {
       array[i] = arabic[hindi.indexOf(array[i])];
     }
   });
   return array.join('');
}

// Example of input
console.log(translate('١٠٠')); // 100

Now you can use your convert function to call it:

var hindi = ['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];
var arabic = [0,1,2,3,4,5,6,7,8,9];

function translate(input) {
   var array = input.split('');
   array.map(function(value, i, array) {
     if (hindi.indexOf(array[i]) >= 0) {
     	array[i] = arabic[hindi.indexOf(array[i])];
     }
   });
   return array.join('');
}

function convert(event) {
    var barcode = document.getElementById("barCode");
    var val = barcode.value;
    barcode.value = translate(val);
}
<input type="text" id="barCode" onkeyup="convert(event)">

Also, you can see it working in this codepen.

Upvotes: 2

Related Questions