Search code examples
javascriptescapingslash

Slash escape in javascript


function slashEscape(strVar){
    var retVal = strVar;
    retVal = retVal.replace(/\\/g,"\\\\");
    return retVal;
}

I use that function to escape the slashes in a certain string. But the result is not right.

var str = slashEscape("\t \n \s");

It will result to "s" instead of "\t \n \s"


Solution

  • When the string constant "\t \n \s" is instantiated to a JavaScript string, it transforms \t to a tab character, the \n to a new line, and \s to a s.

    That's why you can't replace \ with \\ because as far as JavaScript is concerned, there is no \ character. There is only a tab character, a new line, and an s.


    By the way, the result of slashEscape("\t \n \s"); is not "s". It's actually :

    "    
    s"
    

    Which is a tab in the first line, a new line, then an s.