[SalesForce] How to Escape Single Quotation Mark in String.format

I'm using the translation workbench to translate a custom label(mail's body) to English. In the message, there was a word "haven't". When I check the test email, the word showed up as "havent".

I tried using String.escapeSingleQuotes(mailBodyMessage) but it didn't work.

So I went to debug log and check the message retrieved from the custom label. It came out that the message I retrieved from the custom label also didn't have any single quotation marks either.

I tried changing my custom label to "haven\'t" (it showed up as haven\t) and "haven 't" (it showed up as haven 't) but nothing worked.

For now, I deleted all single quotes from my custom label but I still want to know how to fix this problem. Could someone tell me how to escape the quotation mark in custom label? Any help will be much appreciated!

Solution:

I used the code that @Ralph provided and confirmed that there is nothing wrong with custom label. Single quotes disappeared after I formatted the message with String.format(). I googled and found the solution here.

To get a single quote in the output of a string.format requires two escaped single quotes.

So I put haven''t in the custom label and now I got the correct formatted message.

Ralph, Thank you so much for your time. 🙂

Best Answer

That's pretty strange, and seems like a bug since you don't need to do anything in this case to handle single quotes.

It's working for me when I did the following I created a custom label, A_Test, with a value of "haven't", and ran the following and everything worked as expected. Assertions passed and email received with single quote intact. Perhaps you can try this out and see if the assertions fail for you? If they do I'd recommend logging a case with support.

String expected = 'haven\'t';
system.assertEquals(expected, Label.A_Test);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
email.setToAddresses(new String[] { 'ralph@example.com' });
email.setSubject('Expected: ' + expected + '. Label: ' + Label.A_Test);
email.setPlainTextBody('Expected: ' + expected + '. Label: ' + Label.A_Test);
system.assertEquals(true, email.getSubject().contains('\''));
system.assertEquals(true, email.getPlainTextBody().contains('\''));
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });