Thursday, January 28, 2010

How to assign quotation mark in a javascript variable?

For example if you want to put "'"(single quotation mark) into a javascript string variable:

var str = '<tr><td onclick="change('variable')"><img src=apple.jpg border=0></td></tr>';

where variable needs to be replaced with a variable. But variable needs to fit into the string value assignment, this needs to be done:

var str = '<tr><td onclick="change('+variable+')"><img src=apple.jpg border=0></td></tr>';

But the single quotation mark next to '+' will be used as notation in the string assignment.

I also tried this but it won't work using the escape (\) method:

var str = '<tr><td onclick="change(\''+variable+\'')"><img src=apple.jpg border=0></td></tr>';


All I need to do is to assign the part with single quotation mark to a temporary variable to make this trick work:

var temp = "\'"+variable+"\'";

then assign this temp to the str variable I want:

var str = '<tr><td onclick="change('+temp+')"><img src=apple.jpg border=0></td></tr>';

Walla! A trick I used to put a quotation mark in the variable assignment using another variable. I also need the help of the escape (\) character but use it in a separate variable.

A quotation mark in a quotation mark based string assignment. Weird problem and weird solution.

No comments:

Post a Comment