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
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
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>
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);
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" />