首页 > 解决方案 > 正则表达式用零替换 O(Jquery 输入掩码)

问题描述

我正在使用出色的 Igor Escobar Jquery 蒙版插件。( https://igorescobar.github.io/jQuery-Mask-Plugin/ )

在我的输入字段中,我希望它这样如果用户输入字母 O 或 o(大写或小写“o”),它将被零 (0) 替换。

使用文档,我已经能够通过使用翻译来修改正则表达式: $('#myfield').mask('ooo-ooo', {'translation': {'o': {pattern: /^[a-zA-Z0-9]*$/}}});

这种正则表达式模式允许任何字母数字字符,这很棒。但是,我需要修改这个正则表达式,以便将“O”和“o”转换为 0(零)。

这是否可能仅通过使用正则表达式(我不太熟悉),或者是否有更好的 Jquery 掩码功能,我在文档中错过了能够做到这一点?

如果键入,它基本上是用不同的字符替换两个特定字符。非常感谢。

更新:感谢freedomn-m为我指出回调功能的方向,我使用了一些ropey javascript:

var options =  {

  // Replace Os with Zeros
  onKeyPress: function(cep, options){
    var lastChar = cep[cep.length -1];
    if (lastChar=="o" || lastChar=="O") { 
        var newreplace = cep.substring(0, cep.length - 1);
        $('#myfield').val(newreplace + '0'); 
    }
  }
};

$('#myfield').mask('AAA-AAA', options);

标签: jqueryregexmasking

解决方案


推荐阅读