JavaScript and JQuery - Encoding HTML

Posted by user70192 on Stack Overflow See other posts from Stack Overflow or by user70192
Published on 2010-03-30T12:59:41Z Indexed on 2010/03/30 13:03 UTC
Read the original article Hit count: 451

Filed under:
|

Hello,

I have a web page that has a textarea defined on it like so:

<textarea id="myTextArea" rows="6" cols="75"></textarea>

There is a chance that a user may enter single and double quotes in this field. For instance, I have been testing with the following string:

Just testin' using single and double "quotes". I'm hoping the end of this task is comin'.

Additionally, the user may enter HTML code, which I would prefer to prevent. Regardless, I am passing the contents of this textarea onto web service. I must encode the contents of the textarea in JavaScript before I can send it on. Currently, I'm trying the following:

var contents $('<div/>').text($("#myTextArea).val()).html();
alert(contents);

I was expecting contents to display

Just testin&#39; using single and double &#34;quotes&#34;. I&#39;m hoping the end of this task is comin&#39;.

Instead, the original string is printed out. Beyond just double-and-single quotes, there are a variety of entities to consider. Because of this, I was assuming there would be a way to encode HTML before passing it on. Can someone please tell me how to do this?

Thank you,

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery