1

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:

http://jsfiddle.net/59Zau/

//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?

1 Answer 1

6

The problem is in your JSON string. The "\\" there is already a single backslash.

>> console.log("No data \\passed in");
No data \passed in

Are you sure you don't want to just remove all backslashes instead?

obj = obj.replace(/\\/g,"");

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Makes sense--I suppose then I could just do obj = obj.replace(/\\/g,""); because any backslash present in the string at the time of .replace was originally dual backslash.
Well, this function will eventually get applied strings that contain escaped JSON... that's where my headache multiplies. I think this will work though, I'll accept this answer, thanks!
@ElliotB: Why do you even need to replace backslashes? Ideally you should not even have to do this...
I'm working with a proprietary backend whose native method to convert JSON to record structure errors when two or more consecutive backslashes are passed in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.