Hi replaceAll function in apex, is not replacing every occurance in my string. Can anyone guide me on this, how to replace every occurrence in string?

string body='<p>string 1</p><p><img src="sfdc://0684E000000IBcwQAG" alt="Macros ss2"></img></p><p>string 2<img src="sfdc://0694E000000Lqj0QAC" alt="Screen Shot 2018-09-19 at 2.33.01 PM"></img></p><p> </p><p>test sample post</p>';
string a= body.replaceAll(body.substringBetween('src="sfdc://', '"'),'TEST: ');

system.debug('string'+a);


|DEBUG|string<p>string 1</p><p><img src="sfdc://TEST: " alt="Macros ss2"></img></p><p>string 2<img src="sfdc://0694E000000Lqj0QAC" alt="Screen Shot 2018-09-19 at 2.33.01 PM"></img></p><p> </p><p>test sample post</p>

You're only finding the first occurrence, because that's the only ID you end up looking for. Instead, you need to use a regular expression, like this:

String a= body.replaceAll('src="sfdc://.+?"','src="sfdc://TEST: "');

Or, you could match the prefix and suffix:

string a= body.replaceAll('(src="sfdc://).+?(")','$1TEST: $2');

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.