1

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,

2
  • 1
    Forget about HTML encoding in JavaScript. Do it server side. You can't trust the client, so depending on the client to do it is one massive XSS hole. Commented Mar 30, 2010 at 13:15
  • use _.escape from underscorejs.org/#escape Commented Jun 19, 2014 at 7:37

2 Answers 2

3

If you're sending to a web service, you'll presumably be URL-encoding these (as part of a POST, for instance, either via form submission of Ajax). That will handle any necessary escaping at your end. The service at the other end is responsible for interpreting the input string correctly. If the service doesn't accept HTML tags, it's the service's job to do the necessary entity encoding (or whatever other kind of encoding it wants).

If the service doesn't take responsibility for this, it's open to errors in the client and attacks by people with nefarious intent. So it's really the other end's problem.

Sign up to request clarification or add additional context in comments.

Comments

0

By using:

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

You display the textual contents instead of the contents in html.

4 Comments

Isn't something missing here?
@Rafiqunnabi There was, but now I fixed it. Thanks. :-)
You are missing the = operator :)
Added that one too. Weird that nobody noticed this for 3 years (including me). :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.