0

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>
0

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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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