26

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MDuB
  • 361
  • 1
  • 4
  • 15
  • Why are you constructing JSON by yourself rather than using `JSON.stringify`? – Barmar Jul 03 '14 at 17:11
  • 4
    as a sidenote, the regular expression you were using is incorrect, it should be `str.replace(/"/g,'\"')` – Kariudo Oct 17 '14 at 15:48
  • Related: *[Escaping double quotes in JavaScript](https://stackoverflow.com/questions/10241663/escaping-double-quotes-in-javascript)* – Peter Mortensen Jul 19 '20 at 18:10

2 Answers2

25

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"'});
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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

var str = '[{ "Company": "XYZ", "Description": "\\"TEST\\""}]';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
byJeevan
  • 3,728
  • 3
  • 37
  • 60