While working as a Salesforce admin for an organization that tracks leads from multiple sources, I noticed inconsistencies in the Lead Source data. Instead of the web, it was entered as a website, so I had to replace the current lead source value with the web.
To do this, I used the built-in Salesforce Apex function replace() to replace the old string value with the new one. In this Salesforce tutorial, I will explain how to replace a string value in Salesforce Apex.
Syntax to replace a string in Salesforce Apex
Using the replace() function, the syntax for replacing a string in Apex is as follows.
String newString = originalString.replace(oldStringValue, newStringValue);
Replace String Value in Salesforce Apex
To replace a string value in Salesforce Apex, navigate to the Salesforce developer console and follow the steps below.
- In the Salesforce developer console, open the anonymous Apex code window with “Ctrl+E.”
- Enter the code below in the anonymous apex window, and click the Execute button.
String originalString = 'Lead Source - Website';
String replacedString = originalString.replace('Website', 'Web');
System.debug(replacedString);
In the above code, ‘Website’ is the current substring value that is to be replaced with the substring value ‘Web.’
- In the execution log window, select the checkbox to debug only. After this, you will see the replaced value of the substring in the debug.

This way, we can replace a string value in Salesforce Apex using the replace() function.
Replace All Similar String Values in Salesforce Apex
In Salesforce Apex, the replaceAll() method replaces all substring occurrences that match a specified regular expression with another string.
Follow the steps below to replace all occurrences of a substring that match an expression with another string.
- Navigate to the developer console and launch the anonymous apex code window with the shortcut keys “Ctrl+E.”
- Enter the code below in the anonymous window and click the Execute button.
String originalString = 'Lead Source - Website, Referral - Website, Marketing Campaign - Website';
String replacedString = originalString.replaceAll('Website', 'Web');
System.debug(replacedString);
- In the execution log window, select the checkbox to debug only. After this, in the debug, you will see the substring is replaced with the new string value.

This way, we can use the replaceAll() method to replace all substring occurrences that match an expression with another string in Salesforce Apex.