I'm writing code that will generate some javascript. The javascript will involve assigning a variable in the generated code to a string passed into the generator. The generator is also in javascript.
Basically I want to do this:
function generate_code(text) {
return "var a = " + jsEscapeString(text) + "; alert(a);";
}
function jsEscapeString(text) {
// WHAT GOES HERE?
// e.g. it needs to:
// - surround with quotes
// - escape quotes inside the text
// - escape backslashes and newlines and other fun characters
// - defend against other horrible things I probably don't know about
}
I don't want something that only works in the happy case. I want something correct. Something that would survive a malicious adversary trying to do sandbox escapes on the resulting code (e.g. like what you do in the game 'Untrusted').