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.

  • Can you please post your error? – Samuel Dare May 23 '17 at 15:27

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)


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)



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.

  • No problem! If you find that this is the correct solution, please be sure to click the checkmark next to it to allow others to reference this if anyone has the same issue. – Gortonington May 23 '17 at 17:17
  • checkmarked right away, thanks again, works like a charm! – Snowalker May 24 '17 at 12:55
  • @gortonington can't quite get this to work in the way you have it. Trying to understand what the last two numbers are, but can't figure it out. Can you please describe what they represent? – kcalero Nov 11 '19 at 21:31
  • @kcalero - I added more context to my answer and a different script that may help you to better understand and customize. – Gortonington Nov 12 '19 at 14:30
  • Your example actually gives the result "ef" and not "fg". @subStart will be 5. So the substring will start from "e", and not "f" – user3274635 16 hours ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.