-1

I have an MVC app where I'm inserting some text into the DOM using jQuery.

If I use:

$("#toggle").text('<%: translated.Show %>');

The text is rendered.

If I use:

$("#toggle").text("<%: translated.Show %>");

Where resource string is wrapping in double quotes it throws a JavaScript error, note the single quotes wrapping the working version and double quotes wrapping the erroneous version.

Can anyone explain why, I thought there was little difference between single and double quotes in Javascript.

The 'translated.Show' string does not contain quotes just plain text.

CLiown
  • 13,665
  • 48
  • 124
  • 205
  • 2
    Single or double quotes make no difference in JavaScript, except for what needs to be escaped. Your problem is elsewhere. Please provide a reproducible example... I think you will see that your quotes aren't the problem. – Brad Oct 23 '12 at 16:21
  • 1
    my first guess is that what `<%: translated.Show %>` gets rendered into contains quotes – Gabi Purcaru Oct 23 '12 at 16:21
  • 3
    What is the actual source code being output? Let me guess: `translated.Show` contains quotes...?! – deceze Oct 23 '12 at 16:21
  • 2
    It throws a secret Javascript error, or you can show it? ) – raina77ow Oct 23 '12 at 16:21
  • http://stackoverflow.com/questions/3149192/difference-between-single-quotes-and-double-quotes-in-javascript – Brad Oct 23 '12 at 16:21
  • @GabiPurcaru Is on to the answer I think. JSON-encode anything you're sending to JavaScript from the server side. No quotes needed then, and you'll get the right quoting automatically. – Brad Oct 23 '12 at 16:22
  • 1
    If you have a JavaScript problem, then show JavaScript not ASP/JSP/etc that generates JavaScript. If you have a JavaScript error, then tell us what the error is. – Quentin Oct 23 '12 at 16:27

1 Answers1

3

The only difference between double and single quotes in JS is that inside single quotes, single quotes must be escaped while inside double quotes, double quotes must be escaped.

The problem is most likely that the data inside translated.Show contains a double quote (despite your assurances that it does not… quote characters are considered part of plain text).

Make sure your are following Rule 3: JavaScript Escape Before Inserting Untrusted Data into JavaScript Data

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335