+ Start a Discussion

Using HTMLENCODE on an string variable

Hi there,


I tring to use the HTMLENCODE function documented by Salesforce on a string variable,


here is my sample code :


address += a.BillingPostalCode == NULL ? '' : ({!HTMLENCODE(a.BillingPostalCode)});


but it returns the following error : "Error: Compile Error: unexpected token: '{' "


It seems this function is only available when using in an apex component :


<apex:outputText value=" {!HTMLENCODE(myTextField)}" escape="false"/>

is that correct ?


how this possible to this with a string in a variable ?


Any advice would great.




You need to embed the result of the HTMLENCODE expression in a string to make it valid javascript.  

i.e., something like


ddress += a.BillingPostalCode == NULL ? '' : '{!HTMLENCODE(a.BillingPostalCode)}';


should give you what you are looking for.  


Thanks for your answer.


I'm not in javascript code but in an apex controler.


I already tried the synthax you suggest but it returns the string inside the quotes i.e.


instead of the interpreted variable


Ah.   Formula Expressions are only relevent to visualforce markup. 

You may be able to do something similar in apex code by using one of the EncodingUtil methods. 


Thanks for your answer but regarding EncodingUtil documentation, there's no equivalent to hlmlencode function




Return the text, and use the HTMLENCODE function in the Visualforce portion:


public String getSomeHtmlString() { // In Controller
  return '<b>Unencoded HTML text</b>';
{!HTMLESCAPE(SomeHtmlString)} <!-- In Visualforce Page -->






You're right; encodingUtil doesn't have an equivalent method.   You might want to suggest it on the IdeaExchange. 


Meanwhile,  I guess you will either need to code your own, or find a way to push it to the page markup as suggested in another response.