[英]Replace all occurrence of quotes with \quotes within specific quotes
I have a string as below: 我有一个字符串如下:
var tst ='[{"body":"Hi Akhil station siate "U" turjunction,- Immedia"},'
+'{"body":"Hiate "dgt" turjunction,- Immedia"},'
+'{"body":"Hiate "sd turjunction,- Immedia"}]';
I want to replace " by \\" , which is only inside body value 我想更换“的\\”,这是唯一的体内值
This means the string should become 这意味着字符串应该变成
'[{"body":"Hi Akhil station siate \"U\" turjunction,- Immedia"},'
+'{"body":"Hiate \"dgt\" turjunction,- Immedia"},'
+'{"body":"Hiate \"sd turjunction,- Immedia"}]'
It is better if the solution is done using regex. 如果使用正则表达式来解决,则更好。
My motive behind is to make it as a valid JSON so that after parsing I can get array of objects with keys as body and value as string.
我背后的动机是使其成为有效的JSON,以便在解析之后,我可以获得键为主体 ,值为字符串的对象数组。
让Javascript引擎为您完成工作。
var x = JSON.stringify( tst );
Some thing try as follow 一些事情尝试如下
var tst ='{"body":"Hi Akhil station siate "U" turjunction,- Immedia"},'
+'{"body":"Hiate "dgt" turjunction,- Immedia"},'
+'{"body":"Hiate "sd turjunction,- Immedia"}';
tst = tst.replace(/\s("[^"]+?")(?!\})|\s"([^ ]+)/g,function($1)
{
if($1.match(/".+"/))
{
return $1.replace(/"/g,"\\\"");
}
else
{
return $1.replace(/"/g,"\\\"");
}
});
console.log(tst);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.