How to escape special characters from textarea using jQuery?

13,261

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.​

Share:
13,261
user1595858
Author by

user1595858

Updated on June 04, 2022

Comments

  • user1595858
    user1595858 about 2 years

    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.

  • user1595858
    user1595858 almost 12 years
    i am using <textarea> tag and i cannot use .html() along with it. I should use only .val()
  • Jeremy J Starcher
    Jeremy J Starcher almost 12 years
    A URL may consists of many parts. The link I posted is working now, that should explain things.