Wednesday 10 February 2016

Using NewLine in APEX String

String is an awesome DataType provided by Language designers to store any Text Literals(alphabets, numbers, special chars etc) but sometimes Developers need to display Newline Character in the APEX String which can be used on VisualForce Page.

Trick : This can be easily done adding \n for NewLine Character in Apex String and then each \n will be replaced by <br/> in VF page with help of SUBSTITUTE(JSENCODE(Variable), '\\n', '<br/>').

VF Page :
1:  <apex:page controller="Returns">   
2:    <apex:outputLabel value="{!SUBSTITUTE(JSENCODE(choosenText), '\\n', '<br/>')}" escape="false"/ >   
3:   </apex:page>  

Apex Class :
1:  public class Returns{  
2:  public String choosenText{get;set;}  
3:  public Returns(){  
4:  choosenText = 'Hi Salesforce' + '\n' + ' This is a Salesforce Techie Blog.' + '\n' + 'Please share your Feedback';  
5:  }  
6:  }  

Output :
 

Hope this trick is Helpful!!!

4 comments:

  1. Not a good solution since escape="true", makes code vulnerable and gets catched in checkMarx report.

    ReplyDelete
  2. India has been recognized as one of those countries that possess advanced nuclear options, including the production of the raw materials. India is self reliant and has also mustered the expertise to cover the total nuclear cycle right from exploration and mining to generation of power and energy and waste management. Salesforce training in India



    ReplyDelete