简体   繁体   English

如何用转义符代替双引号?

[英]How do I replace double quotes with its escape?

var string = "{ "Name": ""Jack"" }"

I want to replace the double quotes with \\" so that the variable becomes a valid JSON. 我想将双引号替换为\\“,以便该变量成为有效的JSON。

so, it should end up looking like this: 因此,它应该最终看起来像这样:

string = "{ "Name": \""Jack"\" }"

I know you can use the replace function but I'm not getting it to work. 我知道您可以使用replace函数,但无法正常工作。

Put a backslash in front of each double quote that should be escaped. 在每个应该被转义的双引号前面加上一个反斜杠。

var string = "{\"Name\":\"\\\"Jack\\\"\"}"

However, your questions very much looks like an XY problem where you are trying to do something in the completely wrong way! 但是,您的问题非常像XY问题,您正在尝试以完全错误的方式进行操作! You usually never have to deal with escaping etc. when JSON is involved. 当涉及JSON时,通常无需处理转义等问题。

Initially you probably have an object. 最初,您可能有一个对象。 Let's assume obj = {Name: "Jack"} . 假设obj = {Name: "Jack"} Now you apparently want to JSON-encode it. 现在您显然想对其进行JSON编码。 In JavaScript you use JSON.stringify(obj) for it, in PHP you'd do json_encode($obj) . 在JavaScript中,您可以使用JSON.stringify(obj) ;在PHP中,您可以使用json_encode($obj) However, if you want to assign this to a JS variable, you can just put the encoded JSON right after obj = , like this. 但是,如果要将其分配给JS变量,则可以像这样将编码后的JSON直接放在obj =之后。 If you really have to put a JSON string somewhere, you can simply run the JSON encoder over the string again (that's how I created the string in this post): 如果确实需要在某个位置放置JSON 字符串 ,则只需再次对字符串运行JSON编码器(这就是我在本文中创建字符串的方式):

JSON.stringify(JSON.stringify({Name: 'Jack'}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM