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('<', '<'); htmlEncodingMap.put('>', '>'); htmlEncodingMap.put('"', '&quot;'); htmlEncodingMap.put('&', '&'); 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('<', '<'); htmlDecodingMap.put('>', '>'); htmlDecodingMap.put('&quot;', '"'); htmlDecodingMap.put('&', '&'); for (String token : htmlDecodingMap.keySet()) { s = s.replace(token, htmlDecodingMap.get(token)); } return s; }
Answer
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 =
'"<Black&White>"';
String s2 =
s1.escapeHtml4();
System.debug(s2);
// Output:
// "<Black&
// White>"
String s1 =
'"<Black&White>"';
String s2 =
s1.unescapeHtml4();
System.assertEquals(
'"<Black&White>"',
s2);
Attribution
Source : Link , Question Author : LMcDonald , Answer Author : Andrew Fawcett