Replace special characters in Salesforce Apex

Replace special characters in Salesforce Apex

Regular Expression can be used in replaceAll() String method to replace all the special characters from the string in Salesforce Apex.

In the following sample Apex code, I have removed all the special characters from the String. Instead of ”, you can use a replacement character if you have a requirement to replace it with some character.

Sample Apex Code:

String tempStr = 'Infallible-Techie@!#$%^&*()_-+=Testing';
tempStr = tempStr.replaceAll( '[^a-zA-Z0-9]', '' );
System.debug(
    'tempStr is ' +
    tempStr
);

Leave a Reply