I'm afraid to say that answer given by Alex is rather incorrect, to put it mildly:
This function
escape = function (str) {
// TODO: escape %x75 4HEXDIG ?? chars
return str
.replace(/[\"]/g, '\\"')
.replace(/[\\]/g, '\\\\')
.replace(/[\/]/g, '\\/')
.replace(/[\b]/g, '\\b')
.replace(/[\f]/g, '\\f')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r')
.replace(/[\t]/g, '\\t')
; };
appears to be a better approximation.