Escape quotes in a string with backslash
I have a string: " \" "
. I would like to escape all unescaped double-quotes, i.e. add a backslash before "
if it's note there.
input = '" \\" "'
input.replace(???) == '\\" \\" \\"'
I've tried
input.replace(/(?!\\)"/g, '\\"')
It escapes second backslash twice ('\" \\" \"'
) for the reason I don't understand.
I've figured out
(' ' + input).replace(/([^\\])"/g, '$1\\"').slice(1)
But it looks ugly. It has to be开发者_Python百科 a better way.
Update:
One more test case:
>> input = '" \\" \\\\" \\\\\\"'
-> '" \" \\" \\\"'
>> input.replace(???)
-> '\" \" \\\" \\\"'
None of my regular expressions can handle it.
What I have is scarcely better, but it does handle escaped backslashes too:
>>> var v= 'a\\"b'
>>> v
"a\"b"
>>> v.replace(/(\\*)(")/g, function(x) { var l = x.length; return (l % 2) ? x : x.substring(0,l-1) + '\\"' } )
"a\\"b"
>>> var v= 'a\\\\"b'
>>> v
"a\\"b"
>>> v.replace(/(\\*)(")/g, function(x) { var l = x.length; return (l % 2) ? x : x.substring(0,l-1) + '\\"' } )
"a\\"b"
If there are an odd number of slashes before a quote (1, 3, 5), the quote is already escaped; an even number (including zero), in needs escaping.
Made all the harder to read by the necessary of escaping the slashes in input and by the inability of the colorizer to understand the regexp expression...
Of course, you probably shouldn't even be doing this. If you have a raw string and you need something you can pass to (e.g.) eval
, consider $.toJSON
.
This worked for me:
var arf = input.replace(/(^|[^\\])"/g, '$1\\"');
It says, replace a quote, when preceded by beginning-of-string or anything-other-than-backslash, with backslash followed by quote.
String(str).replace(/[\\"']/g, "\\$&")
.replace(/[\r\n\u2028\u2029]/g,
function (x) {
switch (x) {
case '\n': return "\\n";
case '\r': return "\\r";
case '\u2028': return "\\u2028";
case '\u2029': return "\\u2029";
}
})
The String
call ensures that the input is a valid string.
The first replace will handle quotes and backslashes. The second handles embedded line terminators.
If you want to deal with an already quoted string, you can change the first replace to this:
'"' + String(str).replace(/^"|"$/g, "").replace(/[\\"]/g, "\\$&") + '"'
to unquote and requote.
精彩评论