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(
The accepted answer is perfect for digits only but I came across a scenario where the input can be any string (credit card numbers, phone numbers, secret questions etc) and if we want to achieve the same on that (i.e. masking all characters except the last 4) then you can use the following:
str.replace(/.(?=\d{4})/g, "#")
My requirement was to replace it with # sign. The point is to use ., which is for any single character check. The explanation of accepted answer still holds, this just works for any characters and not only digits. Hope it will help someone