What is the best way to do HTML encoding and decoding in Apex?

I am programmatically building a HTML string in Apex and then saving it to a rich text field. The problem is that SalesForce is doing some HTML encoding on the string before it gets persisted which is making the string longer and causing a STRING_TOO_LONG error. What is the best way to do HTML encoding and decoding in Apex? See below for my attempt:

public String htmlEncode (String s) {  

    Map<String, String> htmlEncodingMap = new Map<String, String>();
    htmlEncodingMap.put('<', '&lt;');
    htmlEncodingMap.put('>', '&gt;');
    htmlEncodingMap.put('"', '&amp;quot;');
    htmlEncodingMap.put('&', '&amp;');

    for (String token : htmlEncodingMap.keySet()) {
        s = s.replace(token, htmlEncodingMap.get(token));

    return s;

public String htmlDecode (String s) {  

    Map<String, String> htmlDecodingMap = new Map<String, String>();
    htmlDecodingMap.put('&lt;', '<');
    htmlDecodingMap.put('&gt;', '>');
    htmlDecodingMap.put('&amp;quot;', '"');
    htmlDecodingMap.put('&amp;', '&');

    for (String token : htmlDecodingMap.keySet()) {
        s = s.replace(token, htmlDecodingMap.get(token));
    return s;


The Apex String class has HTML escape and unescape methods on it, escapteHtml4 and unescapeHtml4. Here are some examples from these topics in the documentation…

String s1 = 
String s2 = 
// Output:
// &quot;&lt;Black&amp;
// White&gt;&quot;

String s1 = 
String s2 = 

Source : Link , Question Author : LMcDonald , Answer Author : Andrew Fawcett

Leave a Comment