Strange behavior of Salesforce String.format method

Today I have found some very strange behavior of Salesforce String.format method.

It doesn’t work with single quotes. Later I have found solution posted by Daniel Balinger.

He explains why we need to use double apostrophes instead of single quote

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'?

 

This entry was posted in apex, salesforce, Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s