1

Is it possible to show only first and last character of a password with javascript? Like this: ***** -> e***4

Thank you very much for your help

acqueron
  • 43
  • 5
  • It would not be complicated to use the key event of an input to store the password in a var and use a copy where you replace the content with '*'. Have you tried ? – AxelH Oct 20 '17 at 07:22
  • 4
    Stack Overflow is **NOT** a code writing service. We are always glad to help and support new coders *but you need to help yourself first. :-)* You are expected to try to write the code yourself. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Filnor Oct 20 '17 at 07:22
  • Is there *any* reason why is this desirable? Users don't need to see what their passwords are... not when they're typing on the screen. – Terry Oct 20 '17 at 07:28
  • see [this](https://stackoverflow.com/a/46281083/492258) – asdf_enel_hak Oct 20 '17 at 07:33
  • It's uniquely to allow user to have a quick idea of the structure of his field password after entering it in a input type... – acqueron Oct 20 '17 at 07:34
  • Great! I will try. Many thanks – acqueron Oct 20 '17 at 07:36

3 Answers3

1

You can change the value of password to hidden values, and make its type property from password to 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>
Duc Filan
  • 6,769
  • 3
  • 21
  • 26
0

Regex is a bit strange here since you have to count the amount of chars between the first and last letter. But you can do it with substrings or arrays much simpler.

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);
Alex
  • 9,911
  • 5
  • 33
  • 52
0

There you go! You just need to get the concept of dealing with strings with substr and slice. And just some regex too.

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, "*");
  }
});
<input type = "text" id = "password" />
Sanjay
  • 540
  • 2
  • 13
  • 29