You should use WPL:
Write("var myVar=" + Encoder.JavaScriptEncode(MyData, true) + ";");
if you don't want to reference the library, you can use the following function (adapted from the .Net source):
public static void QuoteString(this string value, StringBuilder b) {
if (String.IsNullOrEmpty(value))
return "";
var b = new StringBuilder();
int startIndex = 0;
int count = 0;
for (int i = 0; i < value.Length; i++) {
char c = value[i];
// Append the unhandled characters (that do not require special treament)
// to the string builder when special characters are detected.
if (c == '\r' || c == '\t' || c == '\"' || c == '\'' || c == '<' || c == '>' ||
c == '\\' || c == '\n' || c == '\b' || c == '\f' || c < ' ') {
if (b == null) {
b = new StringBuilder(value.Length + 5);
}
if (count > 0) {
b.Append(value, startIndex, count);
}
startIndex = i + 1;
count = 0;
}
switch (c) {
case '\r':
b.Append("\\r");
break;
case '\t':
b.Append("\\t");
break;
case '\"':
b.Append("\\\"");
break;
case '\\':
b.Append("\\\\");
break;
case '\n':
b.Append("\\n");
break;
case '\b':
b.Append("\\b");
break;
case '\f':
b.Append("\\f");
break;
case '\'':
case '>':
case '<':
AppendCharAsUnicode(b, c);
break;
default:
if (c < ' ') {
AppendCharAsUnicode(b, c);
} else {
count++;
}
break;
}
}
if (b == null) {
b.Append(value);
}
if (count > 0) {
b.Append(value, startIndex, count);
}
return b.ToString();
}