Search code examples
jqueryhtml-encodeace-editor

How to HTML encode contents of a div in jQuery for use in Ace editor?


Goal

Change content of a div into HTML encoded content for use in Ace editor.

Attempted Solution

I am trying to follow the solution here:

https://stackoverflow.com/a/1219983/1063287

With:

HTML

<div id="encode_me"><html>test</html></div>

jQuery

my_value = $("#encode_me");
$('<div/>').text(my_value).html();

jsFiddle

http://jsfiddle.net/rwone/3bFKG/8/

It is just outputting the text test.

Edit: Alternatively, there is a newer answer on that page that suggests:

function htmlEscape(str) {
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}

And I tried to implement that in a jsFiddle with the same results as the first attempt:

HTML

<div id="encode_me"><html>test</html></div>

jQuery

my_value = $("#encode_me");

my_value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

jsFiddle

http://jsfiddle.net/rwone/6n2fR/


Solution

  • I ran into lots of problems when trying to implement this.

    Basically <html> tags were always stripped out and I couldn't find a way to access the html markup before the tags were stripped or to encode the html within the div containing the markup. jQuery's text() and html() and various combinations of them did not work.

    Solution

    This was the solution that eventually worked for me.

    http://jsfiddle.net/rwone/rAFSZ/1/

    HTML

    <div id="my_html"></div>
    
    <!-- this works using <xmp> tags and NOT when using <div> tags -->
    
    <xmp id="my_html_hidden"><html>test</html></xmp>
    

    jQuery

    The approach I used was to set the value like this:

    var html_editor = ace.edit("my_html");
    // other editor settings
    html_editor.session.setValue($("#my_html_hidden").text());
    

    So the logic of this is that the content was loaded into a hidden div from the database, and then the value of the editor was set with the contents of this hidden div, with the text() method applied.

    The key was that using <xmp> tags did NOT strip the <html> tags, whereas using <div> tags did.