用特定引号内的 \quotes 替换所有出现的引号

Replace all occurrence of quotes with \quotes within specific quotes

我有如下字符串:

var tst ='[{"body":"Hi Akhil station siate "U" turjunction,- Immedia"},'
         +'{"body":"Hiate "dgt" turjunction,- Immedia"},'
         +'{"body":"Hiate "sd turjunction,- Immedia"}]';

我想用 \" 替换 ",这只是内部值

这意味着字符串应该变成

'[{"body":"Hi Akhil station siate \"U\" turjunction,- Immedia"},'
             +'{"body":"Hiate \"dgt\" turjunction,- Immedia"},'
             +'{"body":"Hiate \"sd turjunction,- Immedia"}]'

最好使用正则表达式解决。

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.

让 Javascript 引擎为您完成工作。

var x = JSON.stringify( tst );

一些事情尝试如下

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()
    {
        if(.match(/".+"/))
        {
            return .replace(/"/g,"\\"");
        }
        else
        {
            return .replace(/"/g,"\\"");
        }
     });


console.log(tst);

Online demo