JavaScript - Escape double quotes

后端 未结 2 417
北海茫月
北海茫月 2020-12-01 14:17

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

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


        
相关标签:
2条回答
  • 2020-12-01 14:44

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

    var str = '[{ "Company": "XYZ", "Description": "\\"TEST\\""}]';
    
    0 讨论(0)
  • 2020-12-01 14:48

    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"'});
    
    0 讨论(0)
提交回复
热议问题