将textinput中的数字从阿拉伯语替换为英语并接受负数?

时间:2017-01-29 09:51:49

标签: javascript numbers persian

我编写此代码,当用户开始在testinput中键入其工作正常时将阿拉伯数字转换为英文数字但是如何使其能够接受负值它会阻止我在数字输入上键入( - )

jQuery(document ).on( "keyup", ".number", function(){
 var yas =$(this).val();
yas = Number( yas.replace(/[٠١٢٣٤٥٦٧٨٩]/g, function(d) { return   d.charCodeAt(0)-1632;}).replace(/[٠١٢٣٤٥٦٧٨٩]/g, function(d) {return d.charCodeAt(0) - 1776;}) );
  if (isNaN (yas))
  {yas= 0;}
 $(this).val(yas);

 });

1 个答案:

答案 0 :(得分:0)

String.prototype.toEnglishDigits = function () {
    var persian = { '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9' };
    var arabic = { '٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9' };
    return this.replace(/[^0-9.]/g, function (w) {
        return persian[w] || arabic[w] || w;
    });
};

jQuery(document ).on( "keyup", ".number", function(){
    var yas =$(this).val();
    yas = Number( (yas || '').toEnglishDigits() );
    if (isNaN (yas))
        yas = 0;
    $(this).val(yas);
 });



String.prototype.toEnglishDigits = function () {
    var persian = { '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9' };
    var arabic = { '٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9' };
    return this.replace(/[^0-9.]/g, function (w) {
        return persian[w] || arabic[w] || w;
    });
};

console.log('-۱۲۳۴.۵۶۷'.toEnglishDigits());