Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking last 4 digits in JavaScript

Here I am using regex pattern to mask last 4 digits for Credit Card number.

$("#ccnumber").html(ccnbr); //ccnumber refers to div ID

$("#ccnumber").text(function(_, val) {
  return val.replace(/\d{12}(\d{4})/, "************$1");
});

It is applicable for only 16 digit credit card numbers. But, I need to mask the incoming numbers (may be 10 or 11) by * and show the last 4 digits.

Is it possible in javascript/jQuery?

$('#ccnumber').text(function(_, val) {
  return val.replace(/\d{12}(\d{4})/, "************$1");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ccnumber">1234567891234567</div>
like image 906
UI_Dev Avatar asked Dec 18 '14 11:12

UI_Dev


People also ask

How do I mask a number in JavaScript?

replace(/\d(? =\d{4})/g, "*"); to mask all but last 4 digits in a given number of more than 4 digits.

How do I mask an email address in JavaScript?

const masked = 'r... [email protected]'; We are required to write a JavaScript function that takes in an email string and returns the masked email for that string.

How do I mask my credit card number in react?

Just change the mask to 9999 9999 9999 9999 and it will work for your case. You can use dynamic masks if later you want to change the credit card mask based on the value (because some credit cards have different masks).

How do you mask numbers in C#?

In C#, MaskedTextBox control gives a validation procedure for the user input on the form like date, phone numbers, etc. Or in other words, it is used to provide a mask which differentiates between proper and improper user input.


1 Answers

You can use:

str = str.replace(/\d(?=\d{4})/g, "*");

to mask all but last 4 digits in a given number of more than 4 digits.

RegEx Demo

Explanation:

  • This reges uses a positive lookahead (?=\d{4}) which means match should be followed by 4 digits.
  • \d matches a single digit with above lookahead condition and replaces that by *
like image 121
anubhava Avatar answered Oct 21 '22 15:10

anubhava