Masking (mildly) sensitive data values using Velocity

Community user JW asked a surprisingly unprecedented (AFAIK) question today:

I am looking to send out a communication to our customers that includes that persons Policy Number. Unfortunately our legal department will not let us send the entire {{lead.Policy Number}} digitally. We are permitted to send the last 4 digits however... with Velocity Scripting can I get it to show as *****3253?

Let’s be clear: this isn’t relevant to credit card numbers or SSNs because those fields would never be in Marketo in the first place! (Right, guys?)

But other fields – like Policy Number here, or other account/lead info like the person’s phone number – legitimately would be present in Marketo and your CRM, yet might be nice to partially redact in emails. In the unlikely event that an email is intercepted, the person’s privacy is protected, but there’s still enough data to know they’re the right recipient.

So here’s a quick one-liner to mask out 1234567890 to ******7890:

${lead.PolicyNumber.replaceAll(".(?=.{4,}$)","*")}

In brief, it’s a regex lookahead and replace. The pattern matches any character that has 4 or more characters between it and the end of the string, ergo, all characters except the last 4.

(Yes, there are ways to do this with indexOf and substring instead, possibly more efficiently than the regex… if you’re timing to the microsecond, that is. But as always with Velocity, saving a few lines of code is worth a few μs.)