Reputation: 18296
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').
Upvotes: 1
Views: 90
Reputation: 700650
You would need to escape backslash, the string delimiter, and control characters:
function jsEscapeString(text) {
return '"' +
text
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(/\b/g, '\\b')
.replace(/\v/g, '\\v')
.replace(/\f/g, '\\f')
+ '"';
}
Upvotes: -1
Reputation: 324760
Super easy.
function jsEscapeString(text) {
return JSON.stringify(text);
}
No matter what you put in, you will ALWAYS get a valid representation of it that can be dumped into JS source. The result, when executed, will always be exactly what you put in.
This even works for strings, booleans, numbers, arrays, objects... basically everything you'll ever need.
Although I'm curious as to why you're doing this... This smells of eval
fishiness...
Upvotes: 4