This is my current solution. It works by converting to JSON format, unescaping the doublequotes, escaping single quotes and then replacing the outer double quotes with single quotes.
// Changes a double quoted string to a single quoted one
function doubleToSingleQuote(x) {
return x.replace(/\\"/g, '"').replace(/\'/g, "\\'").replace(/^"|"$/g, "'");
}
// Encodes a string as a single quoted string
function asSingleQuotedString(x) {
return doubleToSingleQuote(JSON.stringify(x));
}
This method also works for arbitrary data structures, by utilizing this regexp for finding all quoted strings:
// Encodes as JSON and converts double quoted strings to single quoted strings
function withSingleQuotedStrings(x) {
return JSON.stringify(x).replace(/"(?:[^"\\]|\\.)*"/g, doubleToSingleQuote);
}