views:

381

answers:

4

I thought that escaping quote characters in javascript was done by either using the other style of quote

"xxx ' yyy"

or

'xxx " yyy'

or using a backslash to quote them

'xxx \' yyy\'

or

"xxx \" yyy"

but that doesn't seem to work in the problem I am currently working on.

The code I want to put in my generated HTML is:

<input type="text" value="MyValue" name="MyName" 
    onChange="MyFunction(this, 0, 99999, ['XXX', this.value, 'YYY']);">

The question is what escaping is needed for the string YYY?

I thought escaping single quote (') would be fine, but then I would also need to escape double quote (") as that is the outer wrapper for the onChange code.

Lets say the string I want for YYY is:

SQ' DQ" LT< GT> AMP&

so I tried outputting

<input type="text" value="MyValue" name="MyName" 
     onChange="MyFunction(this, 0, 99999,
         ['XXX', this.value, 'SQ\' DQ\" LT< GT> AMP&']);">

but FireFox saw the "<" as breaking the code

Eventually, to keep FireFox happy, I had to use

SQ\' DQ\x22 LT\x3C GT\x3E AMP\x26

i.e.

<input type="text" value="MyValue" name="MyName"
    onChange="MyFunction(this, 0, 99999,
        ['XXX', this.value, 'SQ\' DQ\x22 LT\x3C GT\x3E AMP\x26']);">

this is a heck of a lot more escaping than I had expected. Is it really necessary, or have I missed something more straightforward?

Thanks.

+3  A: 

You're escaping on the wrong level - before it even gets to parsing the javascript, it needs to parse the HTML it's embedded in.

Use the HTML entities &quot;, &lt; and &gt; and you'll be fine.

<input type="text" onChange="MyFunction(... ['&quot; &lt; &gt; &quot;']);">
Greg
+1 - I wasn't thinking clearly about what he was doing, I was too focused on what he wrote, and your suggestion of the entities is better.
James Black
A: 

Why not break it up: innerHTML = ' ' + "AMP&']);" + '">';

This leads me to think you have a problem with your design though, and you may want to rethink what you are doing.

For example, you should do this with DOM functions, then this problems becomes simpler, rather than trying to do all this in innerHTML.

James Black
A: 

In xml/html attributes symbols < and > should be escaped: &lt; and &gt;

Anatoliy
+1  A: 

The problem is that you need to the escape the code twice. First you need to escape the characters to put them in the Javascript string literal, then you have to HTML encode the entire Javascript code to put it in the onclick attribute in the HTML tag.

First, to encode the string in the Javascript, it would look like this:

MyFunction(this, 0, 99999, ['XXX', this.value, 'SQ\' DQ" LT< GT> AMP&']);

Then you HTML encode the entire script. In this case there are only characters that need encoding inside the string:

<input type="text" value="MyValue" name="MyName"
   onChange="MyFunction(this, 0, 99999,
   ['XXX', this.value, 'SQ\' DQ&quot; LT&lt; GT&gt; AMP&amp;']);">
Guffa