用反斜杠在字符串中转义引号 [英] Escape quotes in a string with backslash
问题描述
\
我想逃避所有未转义的双引号,即在之前添加反斜杠
如果它在那里记录。 input ='\\'
input.replace(???)=='\\\\\\'
我试过
input.replace(/(?! \\)/ g,'\\'')
它转义第二个反斜杠两次('\\\\'
)因为我不明白。
我已经想到($)$ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ \\')。slice(1)
但它看起来很丑陋,必须一个更好的方法。
更新:
另外一个测试用例:
>> input ='\\\\ \\\\ \\\\\\'
- >'\\\\\\'
>> input.replace(? ?)
- >'\\\\\\\\'
我的正则表达式都不能处理它。
这对我有用:
var arf = input.replace(/(^ | [^ \\])/ g,'$ 1\\ \\\');
它表示,替换一个引号,当前以字符串开头或任何其他方式-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 a better way.
Update:
One more test case:
>> input = '" \\" \\\\" \\\\\\"'
-> '" \" \\" \\\"'
>> input.replace(???)
-> '\" \" \\\" \\\"'
None of my regular expressions can handle it.
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.
这篇关于用反斜杠在字符串中转义引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!