You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Escape and Unescape String Methods in Salesforce

By: Venkata


Salesforce provides lot of String methods similar to Java, and most of us familiar with the following string methods such as contains, replace, split, length, etc. This article is about the usage of Escape Html and Unescape Html String methods Salesforce.

Escape String Method

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

  1. String s = ‘”MST Solutions <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 character, and, 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;MST Solutions &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;MST Solutions &lt;BR&gt;&quot; is reverted to its original format i.e. “MST Solutions <BR>”


Consider you have a formula field with return type as String in one of the objects and the String has some 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 the original value of this field to be displayed in User interface, you will need to unescape this escaped string value before you use it. If you do not format it, you will only get the escaped characters.


By using this String methods, we can escape and un escape the strings, as explained in the above example, and especially it will be very useful, when you need to format a String.


Reference: Salesforce String Methods