js探针开发中遇到过这样的问题; \r\n在字符串拼接的时候是有异常问题的,无法用JSON.parse去解析
function setCustomException(exceptionType, causedBy, errorDump) {
if (arguments.length < 1 || arguments.length > 3) {
console.log("onEvent自定义事件参数个数错误");
return;
}
// if (filterData('exceptionType', exceptionType, 'setCustomException', null, false)) {
// return;
// }
if (arguments[0]) {
var exctptionDic = '{"exceptionType":"' + exceptionType;
if (arguments[1]) {
exctptionDic += '","causedBy":"' + causedBy;
} else {
causedBy = "";
}
if (arguments[2]) {
exctptionDic += '","errorDump":"' + errorDump;
} else {
errorDump = "";
}
exctptionDic += '"}';
console.log(exctptionDic)
console.log(JSON.stringify(JSON.parse(exctptionDic)));
}
}
setCustomException("Custom exception type123","Caused by customer.","Custom error dump 0 /\r/\n Custom error dump 1")
解决方案
function specialCharacter(str=''){
if(str===''){
return str
}
if(/\r|\n/g.test(str)){
return str.replace(/\r/g,'\\\\r').replace(/\n/g,'\\\\n')
}
return str
}