Reputation:
On my javascript
<script>
$("#inputCardNo").keydown(function(e){
if(e.keyCode != 8){
var length = $(this).val().replace(/ /g,"").length;
if(length < 12){
var val = "";
for(var i = 0; i < length + 1; i++){
val+="*";
if((i+1)%4 == 0){
val+=" ";
}
}
$(this).val(val);
}
if(length < 12 || length >= 16){
e.preventDefault();
}
}
});
</script>
Here's the live action of this JS FIDDLE DEMO
What I want here is that the first 4 digits will also be unmasked. I've been struggling with my own logic. Could someone point it out to me?
Upvotes: 0
Views: 1766
Reputation: 7139
It can be done as follow:
For masking all digits except the first 4 and last 4
function maskCreditCard(inputString) {
// Mask all digits except the first 4 and last 4
let maskedString = inputString.replace(/\d/g, (match, index) => {
return index > 3 || index < inputString.length - 4 ? '*' : match;
});
return maskedString;
}
Upvotes: 0