有个需求,在向后台提交数据时,将"字符转义后再提交。
前台的数据既有对象格式(或数组),也有JSON格式,我会在ajax请求前,将数据统一转为JSON格式,这个时候,如果输入有",那么,会被转为",数据格式如下:
"{"houseTypeName":"\"good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"}"希望通过正则表达式,改为:
"{"houseTypeName":""good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"}"但是,我实验了/\"/g或者/"/g,都不行,会把所有"转义,这样肯定是不对的。
求正则大神支招,万分感谢!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
可以在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));var a = {"houseTypeName":"\"good","coveredArea":"4567","tablePrice":"4567","buildingId":"9"}; a = JSON.stringify(a); a = a.replace('\\"',"""); console.log(a);$str = '"{"houseTypeName":"\"good","coveredArea":"\"4567","tablePrice":"4567","buildingId":"9"}"'; $str = preg_replace('/\\\"/', '"', $str); print_r($str);PHP 的替换是这样,JS的也可以参照,希望采纳。