Having some trouble with backslashes regular expressions. I want to remove all dual backslashes (or any multiple of 2) that exist on any string property of an object. I do not want to remove single backslashes nor the last backslash in an odd number of backslashes (e.g., leave one backslash remaining in a set of five continuous backslashes \\\\\ -> \).
The code is here:
//removes all dual backslahes on all string properties on an object
var removeDualBackslash = function (obj) {
var ret = null;
if (typeof(obj) == "string") {
obj = obj.replace(/\\\\/g,"");
return obj;
} else if (typeof(obj) == "number") {
return obj;
} else if (typeof(obj) == "array") {
ret = [];
} else {
ret = {};
}
for (var key in obj)
ret[key] = removeDualBackslash(obj[key]);
return ret;
};
var oJSON = {"t4m_data_in":{"no_data":"No data \\passed in."}};
oJSON = removeDualBackslash(oJSON);
console.log(oJSON.t4m_data_in.no_data);
As you can see from the console.log, one of the backslashes remains. Does anyone know what regular expression I need to remove both of them?
The problem is in your JSON string. The
"\\"there is already a single backslash.Are you sure you don’t want to just remove all backslashes instead?
Doing so would remove literal backslashes like
"\\"but would still preserve other escape sequences like"\n"because in those cases the backslash is just in the string literal, not in the actual string.