views:

58

answers:

2

Let's say that I have like this: "\\n", I need to convert it to a string like if the interpreter would do it: \n.

A simple replace like this wouldn't work:

function aaa(s){
    return s.replace(/\\n/gm,'\n').replace(/\\\\/gm,'\\');
}

I need this behaviour:

  • "Line 1\nLine 2" => Line 1<Line break>Line 2
  • "Line 1\\nLine 1" => Line 1\nLine1
+1  A: 

The simplest, and most evil, solution, is to write return eval(s).
Do not do that.

Instead, you need to make a single replace call with a match evaluator, like this:

var escapeCodes = { 
    '\\': '\\',
    'r':  '\r',
    'n':  '\n',
    't':  '\t'
};

return s.replace(/\\(.)/g, function(str, char) {
    return escapeCodes[char];
});

(Tested)

SLaks
It works! I will wait 2 hours until I accept the answer to make sure I get a very optimized solution.
M28
Note that you might want to add more escape codes. Also, this will _completely_ fail to handle `\x64`. If you want to, I'll modify it to handle those.
SLaks
I know, I am modifying it :)
M28
Hint: `/\\\(['"\\bfnrt]|x\d{2}|\d{3}|u\d{4})/g`, then check the first char and react accordingly, calling `parseInt(substr, 8 or 16)`
SLaks
I already finished it :p, I'll accept your answer and post my code.
M28
+1  A: 

Thanks to SLaks for the answer.

Here is the final code:

(function(self,undefined){
    var charMappings = { 
        '\\':   '\\',
        'r':    '\r',
        'n':    '\n',
        't':    '\t',
        'b':    '\b',
        '&':    '\&'
    };
    var rg=(/\\(.|(?:[0-7]{3})|(?:x[0-9a-fA-F]{2})|(?:u[0-9a-fA-F]{4}))/gm);
    self.mapString=function(s){
        return s.replace(rg, function(str, ch) {
            switch(ch.length){
                case 1:
                    return charMappings.hasOwnProperty(ch)?charMappings[ch]:ch;
                case 2:
                case 4:
                    return String.fromCharCode(parseInt(ch,16));
                case 3:
                    return String.fromCharCode(parseInt(ch,8));
            }
        });
    }
})(window);
M28
SLaks
M28