Escape quotes in a string with backslash

眉间皱痕 提交于 2019-12-11 06:22:35

问题


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 a better way.


Update:

One more test case:

>> input = '" \\" \\\\" \\\\\\"'
-> '" \" \\" \\\"'
>> input.replace(???)
-> '\" \" \\\" \\\"'

None of my regular expressions can handle it.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7382115/escape-quotes-in-a-string-with-backslash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!