I have an object that I've entered text with HTML snippets that I want to insert into a page using JavaScript. When the string is passed in the object(s) using Apex, the strings are normalized so that the < character is replaced with &lt; and the > character is replaced with &gt;. I'd like to covert them back and add them using the element.innerHTML property but I'm having issues translating the &lt; back to a <.

Anyone have any ideas?

  • I ended up overcoming the problem by changing so that I store my marked up text with [b] for <b>. Then after the object is translated from Apex to Ajax, I found that this is where the data was being normalized, I replace the [b] tag with <b> and it works fine. I'll just have to add support for some other tags. Global replace of the brackets might cause problems if the user likes them in their text. – Robert Harper Jun 27 '13 at 21:12
  • I couldn't seem to make any of the suggestions work. The problem is in the translation from what is stored to the Ajax message that is sent to the web page. I changed so that using a [b][/b] for storing the script then translating the [b][/b] pair to <b></b> when the handler renders the innerHTML for an element. – Robert Harper Jul 15 '13 at 20:58

If you cannot make it in Apex, you can try doing it in JavaScript instead:

function unescapeHtml(escapedString) {
    return escapedString
        .replace(/&amp;/g, "&")
        .replace(/&lt;/g, "<")
        .replace(/&gt;/g, ">")
        .replace(/&quot;/g, "\"")
        .replace(/&#039;/g, "'");
| improve this answer | |
  • I'd been trying to do .replace( "&amp;", "&" ) but for some reason, it doesn't find the string "&apm;". I'd not thought of using an expression. Thanks. – Robert Harper Jul 18 '13 at 12:47

You can use the unescapeHtml4 method of the String object. Here is an example from the doc:

String s1 = '&quot;&lt;Black&amp;White&gt;&quot;';
String s2 = s1.unescapeHtml4();

On the visualforce page you can use escape="false" parameter of the apex:outputText.

| improve this answer | |
  • The problem is that I am sending an array of the Apex class in the Ajax return. Once it gets to the client side, I can't use that method in the JavaScript. – Robert Harper Jun 27 '13 at 15:19
  • It looks like it is in the translation from the Apex object to the JavaScript object. The underlying Ajax handler must be normalizing the strings when they are passed to the browser. – Robert Harper Jun 27 '13 at 15:27
  • 1
    Just as mast0r said, use escape="false" in Visualforce. Also, you need to render this text in a VF component such as apex:outputText for it to remain in the original format (including escape=false). – Adam Jun 28 '13 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.