且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

javascript regex替换字符串中的所有双引号,除非双引号后跟空格或逗号空格

更新时间:2023-01-14 21:49:13

这是我能做的***的事情,这是因为在JSON中,未转义的引号只能出现在某些地方.

Here's the best I can do, taking advantage of the fact that in JSON an unescaped quote can only occur in certain places.

input = '{"description":"This is my 12" pizza, and I want "thin crust"","value":"1"}';
console.log(input);
output = input.replace(/{"/g, '_OPEN_').replace(/":"/g, '_COLON_').replace(/","/g, '_COMMA_').replace(/"}/g, '_CLOSE_');
output = output.replace(/"/g, '\\"');
output = output.replace(/_OPEN_/g, '{"').replace(/_COLON_/g, '":"').replace(/_COMMA_/g, '","').replace(/_CLOSE_/g, '"}');
console.log(output)

生产

{"description":"This is my 12" pizza, and I want "thin crust"","value":"1"}
{"description":"This is my 12\" pizza, and I want \"thin crust\"","value":"1"}

您可以用不太可能在输入中出现的字符串替换"OPEN","CLOSE"等,如果您不介意正则表达式是含糊的,甚至可以使用控制字符.但是,正如其他人指出的那样,没有一种解决方案在所有情况下都适用.无论您做什么,描述文字中都会出现一个值,这会使您感到困惑,因为与正确生成的JSON不同,您尝试解析的语法是模棱两可的.

You can replace 'OPEN', 'CLOSE' etc with strings less likely to occur in the input, perhaps even control characters if you don't mind the regexes being cryptic. But as others have noted, there is no solution that will work in all cases. No matter what you do, there is a value that could occur in the description text that will mess you up, because unlike properly generated JSON, the syntax you're trying to parse is ambiguous.