JJ.
JJ.

Reputation: 9950

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.

Upvotes: 0

Views: 114

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318468

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'}))

Upvotes: 1

Related Questions