使用反斜杠转义字符串中的引号
我有一个字符串:" \" "
。我想转义所有未转义的双引号,即在 "
之前添加一个反斜杠(如果有注释的话)。
input = '" \\" "'
input.replace(???) == '\\" \\" \\"'
我已经尝试过
input.replace(/(?!\\)"/g, '\\"')
两次转义第二个反斜杠('\" \\" \"'
),因为我不明白。
我已经弄清楚了,
(' ' + input).replace(/([^\\])"/g, '$1\\"').slice(1)
但它看起来很难看。它必须是更好的方法
更新:
还有一个测试用例:
>> input = '" \\" \\\\" \\\\\\"'
-> '" \" \\" \\\"'
>> input.replace(???)
-> '\" \" \\\" \\\"'
我的正则表达式都无法处理它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我所拥有的也好不到哪儿去,但它也能处理转义的反斜杠:
如果引号前有奇数个斜杠 (1, 3, 5),则引号已经被转义了;偶数(包括零),需要转义。
由于需要转义输入中的斜杠以及着色器无法理解正则表达式,这使得阅读变得更加困难......
当然,您甚至可能不应该这样做。如果您有一个原始字符串并且需要可以传递给(例如)
eval
的内容,请考虑$.toJSON
。What I have is scarcely better, but it does handle escaped backslashes too:
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:
It says, replace a quote, when preceded by beginning-of-string or anything-other-than-backslash, with backslash followed by quote.
String
调用可确保输入是有效的字符串。第一个替换将处理引号和反斜杠。第二个处理嵌入的行终止符。
如果你想处理一个已经被引用的字符串,你可以将第一个替换更改为:
取消引用并重新引用。
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:
to unquote and requote.