用反斜杠在字符串中转义引号 [英] Escape quotes in a string with backslash

查看:178
本文介绍了用反斜杠在字符串中转义引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:\我想逃避所有未转义的双引号,即在之前添加反斜杠 如果它在那里记录。

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆