将所有引号替换为特定引号内的\ quotes

时间:2016-05-08 06:02:13

标签: javascript regex str-replace

我有一个字符串如下:

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"}]'

如果使用正则表达式完成解决方案会更好。

  

我的动机是将它作为一个有效的JSON,以便解析后我可以得到   键的对象数组,键为 body ,值为字符串。

2 个答案:

答案 0 :(得分:1)

让Javascript引擎为您完成工作。

var x = JSON.stringify( tst );

答案 1 :(得分:1)

有些事情尝试如下

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);

Online demo