jQuery Javascript 转义双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24559625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Escape Double Quotes
提问by MDuB
How do you escape double quotes if the JSON string is this:
如果 JSON 字符串是这样的,你如何转义双引号:
var str = "[{Company: "XYZ",Description: ""TEST""}]"
I want to escape the secondary double quotes in value TEST.
我想转义值 TEST 中的辅助双引号。
I have tried this but it does not work.
我试过这个,但它不起作用。
var escapeStr = str.replace(/""/g,'\"');
What am I missing?
我错过了什么?
采纳答案by Barmar
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.
首先,我将外引号改为单引号,这样它们就不会与内引号发生冲突。然后我在最里面的引号之前加上反斜杠TEST
,以逃避它们。我避开了反斜杠,以便按字面意思处理。
You can get the same result with use of a JSON function:
使用 JSON 函数可以获得相同的结果:
var str=JSON.stringify({Company: "XYZ", Description: '"TEST"'});
回答by byJeevan
Here inner Quote escaped and entire string taken in single Quote.
这里内部报价转义,整个字符串采用单引号。
var str = '[{ "Company": "XYZ", "Description": "\"TEST\""}]';