【问题标题】:Hide only few character in a password [closed]仅隐藏密码中的几个字符[关闭]
【发布时间】:2017-10-20 16:13:33
【问题描述】:

是否可以使用 javascript 仅显示密码的第一个和最后一个字符? 像这样: ***** -> e***4

非常感谢您的帮助

【问题讨论】:

  • 使用输入的键事件将密码存储在 var 中并使用将内容替换为“*”的副本并不复杂。你试过了吗?
  • Stack Overflow 不是代码编写服务。我们总是乐于帮助和支持新的编码员,但您首先需要帮助自己。 :-) 您应该尝试自己编写代码。请阅读How to create a Minimal, Complete, and Verifiable example
  • 是否有任何理由为什么这是可取的?用户不需要看到他们的密码是什么……而不是当他们在屏幕上打字时。
  • this
  • 独特之处在于让用户在输入类型中输入后可以快速了解其字段密码的结构...

标签: javascript html


【解决方案1】:

您可以将密码的值更改为隐藏值,并将其类型属性从password改为text

$('#hintPassword').click(function(){
  $("#hiddenPassword").val($('#password').val());
  
  var passwordHint = $('#password').val().replace(/(?!^).(?!$)/g, '•');
  
  $('#password').attr('type', 'text');
  $('#password').val(passwordHint);
});

$('#hidePassword').click(function(){
  $('#password').attr('type', 'password');
  $('#password').val($("#hiddenPassword").val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="hiddenPassword">
<input type="password" id="password" value="pa$$w0rd"> <button id="hintPassword">Hint</button> <button id="hidePassword">Hide</button>

【讨论】:

    【解决方案2】:

    这里的正则表达式有点奇怪,因为您必须计算第一个字母和最后一个字母之间的字符数。但是你可以用更简单的子字符串或数组来做到这一点。

    var password = 'Example';
    var parts = password.split('');
    var len = parts.length;
    var chiffred = parts.map(function(val, index) {
      if (0 === index || (len - 1) === index) {
    
      }
      else {
    val = '*';
      }
      return val;
    });
    chiffred = chiffred.join('');
    console.log(chiffred);

    【讨论】:

      【解决方案3】:

      给你! 您只需要了解使用 substr 和 slice 处理字符串的概念。 还有一些正则表达式。

      var input = document.getElementById('password');
      
      input.addEventListener('keydown', function(){
      	if(input.value.length > 1){
        	input.value = input.value.substr(0, 1) + input.value.substr(1, input.value.length).replace(/[\S\s]/g, "*");
        }
      });
      &lt;input type = "text" id = "password" /&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-23
        • 1970-01-01
        • 2018-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多