user1595858 user1595858 - 6 months ago 75
Javascript Question

How to escape special characters from textarea using jQuery?

I want to know if there are any jquery components which automatically take care of special characters.
This basically means converting

&
to
&amp
and also all listed in here, so that when I send data to the backend it stores in that format.
And then while retrieving we need to convert it back from
&amp
to
&
.

We will be using a lot of mathematical symbols so we need a functionality in JavaScript which does that. Also I have seen a rich text editor but we don't need lot of its features such as images, paragraph etc, though we want the text editor to have some icon or something to insert mathematics symbols and source code. In a nutshell, I'm looking something like the Stackoverflow editor, without images.

Answer

You can use jQuery to do this for you:

function htmlEncode(value){
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
}


$(document).ready(function() {
    alert( htmlEncode ("this is a & test") );
});

Code originally from http://www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289.‚Äč