开发者

How to convert a string with escaped characters into a "normal" string

开发者 https://www.devze.com 2023-01-01 22:09 出处:网络
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.

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开发者_StackOverflow社区(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


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)


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消