Wednesday 30 November 2016

Escape and unescape String methods in Salesforce

Introduction
Salesforce provides lot of string methods similar to Java. But most of us familiar with the following string methods such as contains, replace, split, length, etc. This article is regarding the usage of escapeHtml and unescapeHtml String methods.

Escape String Method
This method escapes the characters in a String using HTML 4.0 entities. Consider the below example,

  1. String s = '"Salesforcekings.blogspot.in <BR>"';
  2. System.debug('Before Escape:'+s);
  3. String escapeString = s.escapeHtml4();
  4. System.debug('After Escape:'+escapeString);
             

The above string “MST Solutions <BR>” is formatted as escaped characters, the changes made in the string is below,
is formatted as &quot;
< is formatted as &lt;
> is formatted as &gt;

Unescape String Method

This method unescapes the characters in a String using HTML 4.0 entities. Consider the below example,

  1. String escapedString = '&quot;Salesforcekings.blogspot.in &lt;BR&gt;&quot;';
  2. System.debug('Escaped String:  '+escapedString);
  3. String unescapeString = escapedString.unescapeHtml4();
  4. System.debug('Unescaped String:  '+unescapeString);

 
The above escaped string &quot;Salesforcekings.blogspot.in &lt;BR&gt;&quot; is reverted to the original format i.e. "Salesforcekings.blogspot.in <BR>"

Usage
Consider you have a formula field with return type string in any one of the object and building values to this field using html tags such as <BR>. If you access this field value in Query Editor or Apex class you will get the escaped String values.
If you want this field value what exactly shows in the User interface means you will need to unescape this escaped string value before you need to use. If you do not formatted this means you will only get the escaped characters.

Conclusion
            By using this string methods we can escape and unescape the string based on the above example, it will be useful when you need to format the string.


Reference: New String Methods

No comments:

Post a Comment

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...