javascript - ajax提交数据时,如何用正则表达式替换掉"号?
巴扎黑
巴扎黑 2017-04-10 17:17:31
0
3
269

有个需求,在向后台提交数据时,将"字符转义后再提交。

前台的数据既有对象格式(或数组),也有JSON格式,我会在ajax请求前,将数据统一转为JSON格式,这个时候,如果输入有",那么,会被转为",数据格式如下:

"{"houseTypeName":"\"good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"}"

希望通过正则表达式,改为:

"{"houseTypeName":""good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"}"

但是,我实验了/\"/g或者/"/g,都不行,会把所有"转义,这样肯定是不对的。

求正则大神支招,万分感谢!

巴扎黑
巴扎黑

Antworte allen(3)
迷茫

可以在json对象转为字符串之前迭代整个json对象,对所有字符串的值进行替换后再将json转为字符串提交给后台

//如果你本身是字符串,请先将字符串转为json对象(JSON.parse/或jQuery.parseJSON)
var json = {"houseTypeName":"\"good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"};
for(var key in json)
    if(typeof json[key] ==='string')
        json[key] = json[key].replace(/"/g,'"');
console.log(JSON.stringify(json));
洪涛
$str  = '"{"houseTypeName":"\"good","coveredArea":"\"4567","tablePrice":"4567","buildingId":"9"}"';
$str = preg_replace('/\\\"/', '"', $str);
print_r($str);

PHP 的替换是这样,JS的也可以参照,希望采纳。

大家讲道理
    var a = {"houseTypeName":"\"good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"};
        a = JSON.stringify(a);
        a = a.replace('\\"',""");
        console.log(a);

Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage