Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Escape double quotes

Tags:

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?

like image 434
MDuB Avatar asked Jul 03 '14 17:07

MDuB


People also ask

How do you escape a double quote in JavaScript?

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!

How do you escape characters with double quotes?

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 = '\"';

How do you handle quotes in JavaScript?

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)

How do you escape a string in JavaScript?

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.


2 Answers

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"'}); 
like image 164
Barmar Avatar answered Oct 06 '22 01:10

Barmar


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

var str = '[{ "Company": "XYZ", "Description": "\\"TEST\\""}]'; 
like image 22
byJeevan Avatar answered Oct 06 '22 01:10

byJeevan