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:
- String s = ‘”MST Solutions <BR>”‘;
- System.debug(‘Before Escape:’+s);
- String escapeString = s.escapeHtml4();
- 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 "
< is formatted as <
> is formatted as >
Unescape String Method
This method unescapes the characters in a String using HTML 4.0 entities. Consider the below example,
- String escapedString = ‘"MST Solutions <BR>"’;
- System.debug(‘Escaped String: ‘+escapedString);
- String unescapeString = escapedString.unescapeHtml4();
- System.debug(‘Unescaped String: ‘+unescapeString);
The above escaped string "MST Solutions <BR>" 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