简体   繁体   English

如何掩盖除最后一位数字外的所有内容

[英]How to mask everything except last digit

I am trying to mask everything except last digit using jquery mask but I am not able to get the logic to do it. 我正在尝试使用jquery mask屏蔽除最后一位数字以外的所有内容,但我无法做到这一点。 Below is what I tried so far. 以下是到目前为止我尝试过的。

 $(document).ready(function() { var options = { onKeyPress: function(value, event, currentField, options) { var fieldVal = currentField.val(); var star = ''; for (var i = 0; i < fieldVal.length - 1; i++) { star += '*'; } currentField.val(currentField.val().replace(/(.)(?!$)/g, star)); } } $('.phone').mask('00000', options); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script> <div> <input type="text" class="phone" /> </div> 

The problem you are facing is related to the applied mask , you are using 00000 , and a 0 only accepts a digit as input on that position. 您面临的问题与所应用的mask ,您正在使用00000 ,而0仅接受一个数字作为该位置的输入。 You will need to add a custom translation, as mentioned here , in the options. 您将需要添加一个自定义的翻译,如提到这里 ,在选项。

For generate the new value of the input I will use String.replace() with a custom replacement function to replace all characters by * except the last one. 为了生成输入的新值,我将使用String.replace()和自定义替换函数将所有字符替换为* ,最后一个除外。

Example: 例:

 $(document).ready(function() { var options = { translation: {0: {pattern: /[0-9*]/}}, onKeyPress: function(val, evt, currField, options) { let newVal = val.replace(/./g, (m, o, str) => (o !== str.length - 1 ? '*' : m)); currField.val(newVal); } }; $('.phone').mask('00000', options); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.js"></script> <div> <input type="text" class="phone" /> </div> 

i would suggest to use simple regex here, no need for jquery.mask . 我建议在这里使用简单的regex ,不需要jquery.mask

 $("input[name='phone']").keyup(function() { $(this).val($(this).val().replace(/[^\\d\\*]/g, '').replace(/\\d(?=\\d{1})/g,'*')); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input type="text" class="phone" name="phone" /> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM