tags:

views:

143

answers:

5

Hi I have a problem with a javascript string

var foo = \"<a href="javascript(foo('a','b'))">test</a>\"

This sentence gives me an error

I could have escaped inner " but I am not allowed to change <a href="javascript(foo('a','b'))">test</a> this part

Is there any way to handle this condition?

Thanks, Sourabh

+4  A: 

No, you need to escape the string somehow.

var foo = "<a href=\"javascript(foo('a','b'))\">test</a>";

or

var foo = '<a href="javascript(foo(\'a\',\'b\'))">test</a>';
Greg
A: 

No, there is no way. As the part that you are not allowed to change contains both quotation marks and apostrophes, there is no way to represent it as a string literal in Javascript without changing it.

Perhaps you can put it as a CData literal in an XML island in the page, and let the Javascript read it from there...

Guffa
+1  A: 

Either escape the quotes within JavaScript:

var foo = "<a href=\"javascript(foo('a','b'))\">test</a>";
var foo = "<a href=\x22javascript(foo('a','b'))\x22>test</a>";
var foo = '<a href="javascript(foo(\'a\',\'b\'))">test</a>';
var foo = '<a href="javascript(foo(\x27a\x27,\x27b\x27))">test</a>';

Or escape the quotes within HTML:

var foo = '<a href="javascript(foo(&#39;a&#39;,&#39;b&#39;))">test</a>';
Gumbo
+2  A: 

There is no way to have characters in the string get escaped without escaping them in the string, such as using @-quoted that C# has. for example

string myString = @""Good Morning", said Dave's mother";

You need to escape the characters in the string in JavaScript using \ character.

Russ Cam
+1  A: 

This forum topic seems to have an 'interesting' alternative, at least. It uses multiline comments inside an anonymous function to enable strings containing both " and ', as well as multiline strings.

Edit: According to bucabay (in the comments below), this method no longer works, at least in Firefox 3.5.

Duroth
that is a pretty neat solution. it has no dependencies outside the JS language. embedding it in HTML or XML is externally dependent.
bucabay
I just tested this solution in Firefox3.5 and it doesn't work any more. Comments in function bodies are ignored by the Function.prototype.toString() method.
bucabay
That's a shame. I was at work when I posted my answer, and so couldn't test it myself. Now I'm back home, I don't need to anymore.
Duroth