简体   繁体   中英

Escaping characters in javascript strings

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

ie

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

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;']);">

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;']);">

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.

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

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