Search code examples
coldfusionmasking

Replacing credit card numbers from a memo field in Coldfusion


I have a string from a memo field with some credit cards on it and I want to mask the numbers to show only the last 4 digits. Example:

<cfset str = "Her card no. is 1234567890123456 which is a bogus number.">

How can I make the value of the str to read:

Her card no. is ************3456 which is a bogus number.


Solution

  • How about something like this. You may need to alter the regex digit match maximum, depending on your credit card number range:

    UPDATED 02.07.18

    <cfset str = "Her card no. is 1234567890123456 which is a bogus number.">
    <cfset maskall = true>
    
    <cfset regex = ".*[\s]+([0-9]{8,19})[\s]+.*">
    
    <cfset ccNumberProtected = "">
    
    <cfif REFindNoCase(regex,str)>
      <cfset ccNumber = REReplaceNoCase(str,regex,"\1")>
      <cfif maskall>
        <cfset ccNumberProtected = RepeatString("*",Len(ccNumber))>
      <cfelse>
        <cfset ccNumberProtected = RepeatString("*",Len(ccNumber) - 4) & Right(ccNumber,4)>
      </cfif>
    </cfif>
    
    <cfif Len(Trim(ccNumberProtected))>
      <cfset str = "Her card no. is " & ccNumberProtected & " which is a bogus number.">
    <cfelse>
      <cfset str = "Card number could not be displayed for security reasons">
    </cfif>