user136224
user136224

Reputation: 153

Error using double quotes in a string in javascript

I need to put this string in a variable:

chart cid="20"

but when I escape: \" this way:

AddSettings = AddSettings + "chart cid=\"0\"";

I still get a javascript error and the sentence shows up in the browser insted of get into the AddSetting variable.

I also tried this way:

AddSettings = AddSettings + 'chart cid="0"';

And the same thing happens.

Upvotes: 0

Views: 2518

Answers (6)

epascarello
epascarello

Reputation: 207557

Guessing you are building an html tag? If that is the case html character entities are your friend

<input type="text" value="&#34;Hello Entities&#34;" />

Upvotes: 0

Benjamin Wohlwend
Benjamin Wohlwend

Reputation: 31878

Doublecheck if that is really what causes your problems. Both methods should work. From an interactive FireBug javascript session (which, BTW, is great to test such things):

>>> AddSettings = 'blabla';
"blabla"
>>> AddSettings += 'chart cid="20"';
"blablachart cid="20""

>>> AddSettings = "blabla";
"blabla"
>>> AddSettings += "chart cid=\"20\"";
"blablachart cid="20""

Upvotes: 0

AlbertoPL
AlbertoPL

Reputation: 11529

If you're not using AddSettings before it gets to that line, you will have an error, as AddSettings has not been defined yet when you are adding it to itself. Make sure AddSettings has been defined prior to calling that line.

Upvotes: 0

Max
Max

Reputation: 2581

AddSettings = AddSettings + 'chart cid=\"0\"';

Upvotes: 0

Blixt
Blixt

Reputation: 50187

It's hard to tell what the error is without knowing where you have this code. I'm assuming the code is in HTML, in which case you'll have to escape double quotes differently:

<button onclick="AddSettings += 'chart cid=&quot;20&quot;';">Click me!</button>

The reason for this is because HTML uses entities (&quot;) rather than escaping characters. The value for the onclick attribute will be converted to the following before being executed as JavaScript:

AddSettings += 'chart cid="20"'

Upvotes: 0

Paul
Paul

Reputation: 1208

Can you post your whole javascript? or at least a little bit more? just to make sure there's nothing wrong around it?

Make sure the quotes are the regular quotes - not the special Microsoft Office quotes.

Upvotes: 1

Related Questions