triggersapexsalesforce-service-cloud

What function do I use in a Salesforce apex trigger to trim a text field?


I'm new to writing apex triggers. I've looked through a lot of the apex developer documentation, and I can't seem to find the combination of functions that I should use to automatically trim characters from a text field.

My org has two text fields on the Case object, which automatically store the email addresses that are included in an email-to-case. The text fields have a 255 character limit each. We are seeing errors pop up because the number of email addresses that these fields contain often exceeds 255 characters.

I need to write a trigger that can trim these text fields to the last ".com" before it hits the 255 character limit.

Perhaps I'm going about this all wrong. Any advice?


Solution

  • You can use replace() function in Apex.

    String s1 = 'abcdbca';
    String target = 'bc';
    String replacement = 'xy';
    String s2 = s1.replace(target, replacement);
    

    If you need to use regular expression to find the pattern, then you can use replaceAll()

    String s1 = 'a b c 5 xyz';
    String regExp = '[a-zA-Z]';
    String replacement = '1';
    String s2 = s1.replaceAll(regExp, replacement);
    

    For more information please refer Apex Reference Guide