简体   繁体   中英

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.

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

You didn't say how you were submitting things, but chances are encodeURIComponent will be your friend.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent

The link was down when I posted, but Mozilla should be up and running soon.

函数encodeURIComponent($('#textarea').val())将解决您的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM