简体   繁体   中英

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.

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.

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! You usually never have to deal with escaping etc. when JSON is involved.

Initially you probably have an object. Let's assume obj = {Name: "Jack"} . Now you apparently want to JSON-encode it. In JavaScript you use JSON.stringify(obj) for it, in PHP you'd do 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. 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.stringify(JSON.stringify({Name: 'Jack'}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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