+ Start a Discussion
Daniel BallingerDaniel Ballinger 

Unexpected String.format(String s, List<String> arguments) output with escaped single quotes

The output of the Apex String.format function doesn't seem correct when the format string contains an escaped single quote.

 

E.g. Executing the following Anonymous code in Eclipse

 

 

String formattedString = String.format('Hello {0}, \' shall we play a {1}', new String[]{'David', 'game'});
System.debug(formattedString);
System.debug('before \' after');

 

 

System.debug(formattedString) results in
Hello David,  shall we play a {1}

 

Rather than the expected

Hello David, ' shall we play a game

 

Is this a bug/feature of String.format?

 

I've had a colleague reproduce this issue in a separate install of Eclipse and also seen it with a Chatter FeedPost created by a trigger.

Best Answer chosen by Admin (Salesforce Developers) 
Daniel BallingerDaniel Ballinger

I think I've figured this out.

 

The Apex string.format documentation says:

 

 

Treat the current string as a pattern that should be used for substitution in the same manner as apex:outputText.

 

 

The apex:outputText documentation says:

 

The value attribute supports the same syntax as the MessageFormat class in Java. See the MessageFormat class JavaDocs for more information.

 

 

The java.text.MessageFormat documentation says:

 

Within a String, "''" represents a single quote. A QuotedString can contain arbitrary characters except single quotes; the surrounding single quotes are removed.

 

 

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

 

E.g.

 

String formattedString = String.format('Hello {0}, shall we play a \'\'{1}\'\'?', new String[]{'David', 'game'});  
System.debug(formattedString); 

 

 

Outputs:

 

Hello David, shall we play a 'game'?