Encode HTML before POST
I have the following script, which encodes some of the value it receives propertly, but it does not seem to encode double quotes.
How do I encode the full value properly before posting?
function htmlEncode(value){
return $('<div/>').text(value).html();
}
The above script give me this:
<p>Test&nbsp; <span style="color: #ffffff"><strong><span style="background-color: #ff0000">1+1+1=3</span></strong></span></p>
I need it to give me this:
<p>Test&nbsp; <span style="color: #ffffff"><strong><span style="background-color: #ff0000">1+1+1=3</span&a开发者_运维知识库mp;gt;</strong></span></p>
EDIT: Followup question: Encoded HTML in database back to page
You shouldn't try to encode things with JavaScript.
You should encode it serverside.
Anything that can be done with JavaScript can be undone.
It is valid to encode it in JavaScript if you also check that it was encoded on the server, but keep in mind: JavaScript can be disabled.
What George says is true. But, if you have to encode strings client-side, I'd suggest you use JavaScript's encodeURIComponent().
I had a similar problem. I simply used the replace method in javascript. Here's a nice article to read: http://www.w3schools.com/jsref/jsref_replace.asp
Basically what the replace method does is it swaps or replaces the character it founds with what you indicate as replacement character(s).
So this:
var str=' " That " ';
str = str.replace(/"/g,'"');
Once you log this into the console of your browser, you will get something like
" That "
And this:
var str=' " That " ';
str = str.replace(/"/g,'blahblahblah');
Once you log this into the console of your browser, you will get something like
blahblahblah That blahblahblah
You can use this module in js, without requiring jQuery:
htmlencode
You can re-use functions from php.js project - htmlentities and get_html_translation_table
Use escape(str) at client side
and
HttpUtility.UrlDecode(str, System.Text.Encoding.Default); at server side
it worked for me.
精彩评论