UI_Dev UI_Dev - 3 months ago 52x
Javascript Question

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 ?



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


  • 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 *