tags:

views:

71

answers:

3

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.

A: 

You might want to escape other characters aside from quotes, eg whitespace characters (newlines!) and/or non-ASCII characters. There's Crockford's quote(), and my own implementation can be found at mercurial.intuxication.org.

Christoph
A: 

The answer is that yes, you have to replace literal backslash characters in the string, with two backslashes, BEFORE replacing " with \".

(This does sort of assume that the 'system' that will later parse this quoted string, is written properly.)

the simplest explanation is to consider the 5-character string

foo\"   

After the first 3 characters (foo), there is a literal backslash character in the string, and then there is a literal double quote character.

(Put another way, as a string literal this would look like "foo\\"")

If I were to only replace the quote character, i'd end up with a quoted string whose value was

foo\\"     

When I then tack double quote characters on the beginning and end, this ends up with unbalanced quotes which is bad.

"foo\\""

on the other hand, first replacing all backslashes with double backslashes gives

foo\\"

and then replacing the quote with slash-quote gives

foo\\\"

and when i tack my double quote chars on beginning and end i finally get

"foo\\\""

which is correct. Kind of simple in retrospect.

nmealy
A: 

You might want to avoid escaping quotes you already escaped-

String.prototype.inquotes=function(){
 return '"'+this.replace(/(^|[^\\])"/g,'$1\\"')+'"';
}
kennebec