4

I have a custom label which contains a couple of parameters:

Hello, {0} the other param is {1}.

I wish to output this value in a Visualforce Page like so:

<apex:variable var="firstParam" value="THE_NAME"/>
<apex:variable var="secondParam" value="SECOND_PARAM"/>
<apex:outputText value="{!$Label.Whatever}">
    <apex:param value="{!firstParam}"/>
    <apex:param value="{!secondParam}"/>
</apex:outputText>

This of course outputs this:

Hello, THE_NAME, the other param is SECOND_PARAM.

So far so good. Now, if a translation for this custom label contains an apostrophe -- Hello, {0}, it's the second param: {1}. --, the string interpolation breaks like this:

Hello, THE_NAME, it's the second param: {1}.

I've discovered that I need to double the apostrophe -- Hello, {0}, it''s the second param: {1}. -- to make it work:

Hello, THE_NAME, it's the second param: SECOND_PARAM.

Escaping certain characters in strings is definitely a job for the computer rather than a translator.

What's the Visualforce way to have the single apostrophes in a custom label escaped?

I've tried to call a String replace method on the $Label.Whatever part, but this doesn't even compile. I also couldn't do String($Label.Whatever) to cast it, and I haven't been able to find any solution on the net.

1 Answer 1

2

Theoretically, you should be able to just do:

SUBSTITUTE($Label.Whatever, '\'', '\'\'')

However, I couldn't get SUBSTITUTE or CONTAINS to find the single quote characters until I created a new label with just that character.

SUBSTITUTE($Label.Whatever, $Label.SingleQuote, $Label.SingleQuote & $Label.SingleQuote)

The above approach is nice because it makes you independent of your controller. Additionally, you can write an Apex Class to help out as follows:

public class LabelServices
{
    public static String doubleSingleQuotes(String input)
    {
        return String.isBlank(input) ? input : input.replace('\'', '\'\'');
    }
}
2
  • Thank you, this is working, however it's a bit verbose. I wonder if there's a way to use some kind of static helper method which accepts a Custom Label name and returns the escaped value. I'm new to the Salesforce nomenclature so I'd be grateful for any tips as to what I should be looking for. :) May 11, 2016 at 8:04
  • @Wabbitseason added some code but haven't tested yet.
    – Adrian Larson
    May 11, 2016 at 15:02

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.