4

I'm struggling to use String.format to replace a token with a value when the token is within single quotes:

Example:

String query = String.format('SELECT Id FROM Availability WHERE Person__c = \'{0}\'', personId);

String query is equal to:

SELECT Id FROM Availability WHERE Person__c = {0}

Rather than:

SELECT Id FROM Availability WHERE Person__c = '234567890'
7

Quoting the merge field makes it literal text. In order to get the merge field to work, you have to quote the quotes:

String query = String.format('SELECT Id FROM Availability WHERE Person__c = \'\'{0}\'\'', personId);

The Apex Code documentation states:

Treat the first argument as a pattern and return a string using the second argument for substitution and formatting in the same manner as apex:outputText and the Java MessageFormat class.

The Java documentation for MessageFormat says:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String.

  • 2
    @Robs Yeah, if you're not familiar with Java, and you see a reference to Java in the documentation, you need to also check the Java documentation for caveats. As long as you remember this, you'll be okay. – sfdcfox Mar 10 '18 at 12:05

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.