If you’re looking to replace all occurrences of a substring in Salesforce Apex, the String.replace() or String.replaceAll() methods can help! Let’s break it down:
1. Using replace() (Replaces First Occurrence Only)
The replace() method only replaces the first occurrence of the specified substring.
String text = 'Hello Apex! Apex is fun!';
text = text.replace('Apex', 'Salesforce');
System.debug(text); // Output: "Hello Salesforce! Apex is fun!"
Notice how only the first "Apex" was replaced? That’s because replace() doesn’t target all instances.
2. Using replaceAll() (Replaces All Occurrences)
If you need to replace all instances of a word or phrase, replaceAll() is your go-to method.
String text = 'Hello Apex! Apex is fun!';
text = text.replaceAll('Apex', 'Salesforce');
System.debug(text); // Output: "Hello Salesforce! Salesforce is fun!"
Now, every occurrence of "Apex" is replaced with "Salesforce"