[SalesForce] AMPscript Substring to capture last characters

I tried applying the method someone posted here

AmpScript to select Right or Left characters from a string but "-"

gives me an error in Salesforce Marketing Cloud.

This is my code:

Set @creditcardnumberlastfour = Substring(@creditcardnumber,Length(@creditcardnumber)-4,4)=%%

I try to capture the last 4 characters. What do I do wrong? Thanks.

Best Answer

AMPScript does not recognize '-' as subtract, you need to use the SUBTRACT() function to accomplish this. (Also, you have the =%% tail on this, when it needs to reside inside of an ampscript block)

See below:

%%[

Set @cardnumberlastfour = Substring(@cardnumber, SUBTRACT(Length(@cardnumber), 3), 4)

]%%

EDIT
Adding some extra context as requested by @kcalero:

Below is taken from AMPScript Guide to show the arguments for the function: enter image description here

Basically what I am doing in the above is:

  1. Taking the string (@cardnumber) and placing it into the first argument.
  2. Using math,SUBTRACT(), I find the starting point. For this case since I want to only take the last 4 characters, I take the Length of the string and then subtract 4 from it. Basically, if length is 8, then I use math to set the start point at 8 - 4 = 4. This is then used as the second argument.
  3. The final argument is the length of the substring you want to use. E.g. since we want the last 4, we need this to be 4.

@kcalero - I would do the following:

%%[
    set @string = 'abcdefg'
    set @strLength = Length(@string)
    set @subLength = 2
    set @subStart = Subtract(@strLength,Subtract(@subLength,1))

    set @lastTwoChar = Substring(@string,@subStart,@subLength)
]%%

%%=v(@lastTwoChar)=%%


OUTPUT: fg

This will also give you a reusable script that you can change the string and @subLength to get different lengths of characters without having to change anything else.