Obviously when you're creating an actual string literal yourself, you backslash escape the double quote characters yourself.
var foo = "baz\"bat";
Just as you would with the handful of other control characters, like linebreaks and backslashes.
var bar = "baz\\bat\nmynew line and a \"quote\" ";
but if you're just wrapping that existing variable in quote character, ie to give it to some other system that requires quoted input, there's some confusion.
Obviously you have to escape any potential double quote characters that are in the string.
var doubleQuoteRe = /\"/g;
var quoted = "\"" + unquoted.replace(escaper, '\\\"') + "\"";
But according to some you also now have to worry about escaping literal backslash characters in the variable. In other words using much bigger hammer than my little regex. However i dont see why.