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?
To escape a single or double quote in a string, use a backslash \ character before each single or double quote in the contents of the string, e.g. 'that\'s it' . Copied!
To cause the C compiler to interpret the double quotation mark as a character, precede the double quotation mark with the C escape character, the backslash (\). The following example illustrates the correct syntax for the query in Table 1: EXEC SQL select col1 from tab1 where col1 = '\"';
Javascript uses '\' (backslash) in front as an escape character. To print quotes, using escape characters we have two options: For single quotes: \' (backslash followed by single quote) For double quotes: \” (backslash followed by double quotes)
Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
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"'});
Here the inner quote is escaped and the entire string is taken in single quote.
var str = '[{ "Company": "XYZ", "Description": "\\"TEST\\""}]';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With