Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

How can I use the Apex string replace method for replacing all occurrences in the Salesforce apex code?

Asked by Debbie Jha Apr 3, 2024 4.2K views 3 answers
Share

About this question

I am a Salesforce developer and I am currently working on a custom apex class for data processing within my organization’s Salesforce instance. In this particular task, I need to manipulate the strings by replacing certain substrings with new values. How can I use the Apex string replace method for replacing all occurrences of a specific substring within a given string with another in the Salesforce apex code? 

Your answer

3 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Mar 4, 2025

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"

Was this helpful?

Connie Gerdes

Answered on Mar 4, 2025

Hi! To replace all occurrences of a substring in Apex, you can use String.replace or String.replaceAll method. Or you can visit sprunki modded page for detailed usage.

Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.