MDuB
MDuB

Reputation: 371

JavaScript - Escape double quotes

How do you escape double quotes if the JSON string is the following?

var str = "[{Company: "XYZ",Description: ""TEST""}]"

I want to escape the secondary double quotes in value TEST.

I have tried the following, but it does not work.

var escapeStr = str.replace(/""/g,'\"');

What am I missing?

Upvotes: 27

Views: 104860

Answers (2)

byJeevan
byJeevan

Reputation: 3838

Here the inner quote is escaped and the entire string is taken in single quote.

var str = '[{ "Company": "XYZ", "Description": "\\"TEST\\""}]';

Upvotes: 1

Barmar
Barmar

Reputation: 782285

It should be:

var str='[{"Company": "XYZ","Description": "\\"TEST\\""}]';

First, I changed the outer quotes to single quotes, so they won't conflict with the inner quotes. Then I put backslash before the innermost quotes around TEST, to escape them. And I escaped the backslash so that it will be treated literally.

You can get the same result with use of a JSON function:

var str=JSON.stringify({Company: "XYZ", Description: '"TEST"'});

Upvotes: 25

Related Questions