Masking last 4 digits in JavaScript

后端 未结 7 1691
遥遥无期
遥遥无期 2020-12-09 05:39

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(         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 06:07

    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

提交回复
热议问题