'How to convert Arabic number to English in input number?
I have input type number and need to convert the numbers from Arabic to English once user trying to write:
My wrong shut:
<input type="number" class="arabicNumbers">
Jquery(js) code:
function toEnglishNumber(strNum) {
var ar = [
'٠','١','٢','٣','٤','٥','٦','٧','٨','٩',' ','-','/','|','~','٫'
];
var en = [
'0','1','2','3','4','5','6','7','8','9','','','','','','.'
];
var cache = strNum;
for (var i = 0; i < 10; i++) {
var regex_ar = new RegExp(ar[i], 'g');
cache = cache.replace(regex_ar, en[i]);
}
return cache;
}
$(document).on('keyup', '.arabicNumbers', function() {
toEnglishNumber($(this).val())
});
Any suggestions or slove?
Solution 1:[1]
function replaceBulk( str, findArray, replaceArray ){
var i, regex = [], map = {};
for( i=0; i<findArray.length; i++ ){
regex.push( findArray[i].replace(/([-[\]{}()*+?.\\^$|#,])/g,'\\$1') );
map[findArray[i]] = replaceArray[i];
}
regex = regex.join('|');
str = str.replace( new RegExp( regex, 'g' ), function(matched){
return map[matched];
});
return str;
}
// Test:
console.log( replaceBulk( "??", [
'?','?','?','?','?','?','?','?','?','?',' ','-','/','|','~','?'
], [
'0','1','2','3','4','5','6','7','8','9','','','','','','.'
] ) );
Reference : Replace multiple strings at once
Solution 2:[2]
I'm not quite sure about extra (non-numeric) characters purpose inside your dictionary, however, extending the following logic for arbitrary dictionary is not difficult:
const ar = [...'??????????'],
en = [...'0123456789'],
arToEn = s => s.replace(new RegExp(`[${ar.join('')}]`,'g'), m => en[ar.indexOf(m)])
console.log(arToEn('????'))
Solution 3:[3]
You can do this using Unicode character and hexadecimal offsets like:
function toEnglishNumber(x) {
return x.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, c => c.charCodeAt(0) & 0xf);
}
console.log(toEnglishNumber('??????????'));
Solution 4:[4]
Intl.NumberFormat('ar').format("123456789")
> "???????????"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
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 | Illya |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | Feuda |
