Sourabh
Sourabh

Reputation: 4765

assign javascript string without escaping

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

Upvotes: 17

Views: 20501

Answers (6)

bviale
bviale

Reputation: 5375

Several years later, this is now possible with String.raw()

let foo = String.raw`<a href="javascript(foo('a','b'))">test</a>`

Upvotes: 46

Duroth
Duroth

Reputation: 6581

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.

Upvotes: 1

Russ Cam
Russ Cam

Reputation: 125488

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.

Upvotes: 2

Gumbo
Gumbo

Reputation: 655239

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>';

Upvotes: 2

Guffa
Guffa

Reputation: 700342

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

Upvotes: 0

Greg
Greg

Reputation: 321638

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>';

Upvotes: 4

Related Questions