How do you safely wrap a JS string variable in double quote chars?

Posted by incombinative on Stack Overflow See other posts from Stack Overflow or by incombinative
Published on 2010-03-08T18:11:49Z Indexed on 2010/03/08 20:06 UTC
Read the original article Hit count: 188

Filed under:

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";

but when you already have a variable, and you're wrapping that existing variable in quote characters, there's some confusion.

Obviously you have to escape any potential double quote characters that are in the string. (Assuming whatever system you're giving the explicitly quoted string to, needs to be able to parse them correctly. =)

var doubleQuoteRe = /\"/g;
var quoted = unquoted.replace(escaper, '\\\"');

However from there opinions diverge a little. In particular, according to some you also have to worry about escaping literal backslash characters in the variable.

// now say i have a string bar,  that has both single backslash character in it, 
// as well as a double-quote character in it. 
// the following code ONLY worries about escaping the double quote char. 
var quoted = bar.replace(doubleQuoteRe, '\\\"');

The above seems fine to me. But is there a problem im not seeing?

© Stack Overflow or respective owner

Related posts about JavaScript